Ruby on rails Rails 3嵌套资源和关联(调用contact.note.create时用户id为nil)
我可能会想到一个更好的标题,并开放的建议 我试图在我的NotesController中调用它,并在rails控制台中测试它:Ruby on rails Rails 3嵌套资源和关联(调用contact.note.create时用户id为nil),ruby-on-rails,ruby,ruby-on-rails-3,activerecord,associations,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Associations,我可能会想到一个更好的标题,并开放的建议 我试图在我的NotesController中调用它,并在rails控制台中测试它: ?> u = User.first User Load (1.6ms) SELECT "users".* FROM "users" LIMIT 1 => #<User id: 2, email: nil, password: nil, linkedin_url: nil, created_at: "2012-06-17 05:54:44",
?> u = User.first
User Load (1.6ms) SELECT "users".* FROM "users" LIMIT 1
=> #<User id: 2, email: nil, password: nil, linkedin_url: nil, created_at: "2012-06-17 05:54:44", updated_at: "2012-06-17 05:54:44", liid: "7fB-pQGIQi">
>> c = u.contacts.first
Contact Load (2.0ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = 2 LIMIT 1
=> #<Contact id: 8, user_id: 2, created_at: "2012-06-19 01:23:45", updated_at: "2012-06-19 01:23:45">
>> c.notes.create!(:body => "this is a note")
(0.5ms) BEGIN
SQL (23.3ms) INSERT INTO "notes" ("body", "contact_id", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["body", "this is a note"], ["contact_id", 8], ["created_at", Thu, 21 Jun 2012 05:42:21 UTC +00:00], ["updated_at", Thu, 21 Jun 2012 05:42:21 UTC +00:00], ["user_id", nil]]
(1.7ms) COMMIT
=> #<Note id: 4, created_at: "2012-06-21 05:42:21", updated_at: "2012-06-21 05:42:21", body: "this is a note", user_id: nil, contact_id: 8>
问题出在最后一行,它说创建的便笺有一个用户id:nil。我想知道我遗漏了什么,不允许便笺从联系人用户id正确获取用户id?我可以想出一个快速修复方法,在note对象上设置用户id,但它似乎可以从contact id获取它,我错了吗
以下是我的模型,以防有帮助:
class Contact < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :notes
end
class User < ActiveRecord::Base
attr_accessible :password, :liid
has_many :contacts
has_many :notes, :through => :contacts
end
class Note < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :contact
belongs_to :user
end
谢谢你的帮助 您的便笺还需要属于您的用户:
class Note < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :contact
belongs_to :user
end
嗯,用户id仍然为零。不过,您是对的,我没有在Noteupdated的初始帖子中添加“属于”:user以反映新的rails控制台会话和模型正如您所猜测的,您必须手动在Note对象上设置用户id。更新代码以反映这一点OK,看起来这将是我希望rails比以前更神奇的一次。
c.notes.create!(:body => "this is a note", :user_id => c.user_id)