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

时间:2012-06-21 05:29:54

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

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

我试图在我的NotesController中调用它,在rails console中测试它:

    ?> 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>

问题出在最后一行,它说创建的Note有一个“user_id:nil”。我想知道我错过了哪些不允许笔记正确地从联系人user_id获取user_id?我可以想一个快速修复,在note对象上设置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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的笔记也需要属于您的用户:

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)