【问题标题】:rails application undefined method for class类的rails应用程序未定义方法
【发布时间】:2014-04-06 02:16:59
【问题描述】:

在将脚手架 Review 中的 create 函数与我的 Concert 模型关联后,我重写了它。当我尝试提交表单以创建评论时,虽然我收到一条错误消息

#Class:0xab9972c 的未定义方法“评论”>

def create
    @review = Concert.reviews.create(review_params) 
end

我的 Concert 模型如下所示

class Concert < ActiveRecord::Base

validates_presence_of :artist
validates_presence_of :venue
validates_presence_of :date

has_many :reviews
end

我的 Review 模型看起来像这样

class Review < ActiveRecord::Base

    validates_presence_of :artist
    validates_presence_of :venue
    validates_presence_of :date

    belongs_to :user
    belongs_to :concert
end

我还在迁移文件中添加了关系,但仍然出现错误。有人可以向我解释是什么原因造成的,以及如何创建属于音乐会的评论吗?

【问题讨论】:

    标签: ruby-on-rails-4 model associations has-many belongs-to


    【解决方案1】:

    关联has_many :reviews 是一个实例方法。我怀疑在你的 create 方法中你想要这样的东西:

    def create
        @concert = Concert.new
        @concert.save
        @review = @concert.reviews.create(review_params) 
    end
    

    【讨论】:

    • 我试过了,现在它说“你不能调用 create 除非父级被保存”所以我猜我需要做 Concert.create 而不是 .new
    • 对不起。是的,你需要先做@concert.save。如果您有任何必填字段或其他验证,则必须在保存之前填写这些字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2015-03-06
    相关资源
    最近更新 更多