Rails 3 嵌套资源和关联(调用 contact.note.create 时user_id nil)



(我可能会想到一个更好的标题并接受建议)

我正在尝试在我的 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", 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>

问题出在最后一行,它说创建的注释有一个"user_id:nil"。我想知道我错过了什么,不允许笔记正确获取联系人user_id user_id?我可以想到一个快速解决方案,在笔记对象上设置user_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

Rails 只会自动设置父对象的foreign_key,而不是您想要的父对象的父对象。 因此,您必须手动设置该属性:

c.notes.create!(:body => "this is a note", :user_id => c.user_id)

最新更新