0

(おそらく、これにもっと良いタイトルを考えて、提案を受け入れることができます)

Railsコンソールでテストして、NotesControllerでこれを呼び出そうとしています:

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

助けてくれてありがとう!

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 に答える