【问题标题】:Rails 3, Modeling QuestionRails 3,建模问题
【发布时间】:2010-09-11 16:37:53
【问题描述】:

rails 3 新手,使用 Devise 进行身份验证...

我想创建以下模型:

class Instance < ActiveRecord::Base
 has_many :users
 has_many :notes
end 

class User < ActiveRecord::Base
 belongs_to :instance
end

class Note < ActiveRecord::Base
 belongs_to :instance
end

在 notes_controller.rb 中创建新笔记

def create
 @note = instance.notes.build(params[:note].merge(:instance_id => current_user.instance_id))
end

但我收到以下错误:“未定义的局部变量或方法 `instance' for #”

想法?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3


    【解决方案1】:

    您尚未为“实例”分配任何内容,因此没有可参考的内容。如果您知道数据库中已经存在实例记录,您可以执行以下操作:

    @instance = current_user.instance
    @note = Note.create(:instace_id => @instance.id)
    

    如果没有,您需要先检查并在必要时使用相同的语法创建它。

    【讨论】:

    • 这属于笔记的控制器,对吗?
    • @nobosh 是的。当您点击相应的链接时,该代码会被调用,例如/notes/create,然后您在该控制器方法中声明的任何实例变量也可以在视图中访问。
    • 感谢 bnaul,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多