0

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

我试图在我的 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>

问题出在最后一行,它说创建的 Note 有一个“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

谢谢您的帮助!

4

1 回答 1

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)
于 2012-06-21T05:33:40.863 回答