class User < ActiveRecord::Base
attr_accessible :email, :password, :picture, :username
has_many :entries, :class_name => "Entry", :inverse_of => :user
has_many :sent_messages, :inverse_of => :sender, :class_name => "Message", :foreign_key => "sender_id"
has_many :recieved_messages, :inverse_of => :target, :class_name => "Message", :foreign_key => "target_id"
has_many :mails, :inverse_of => :user
...
end
class Message < ActiveRecord::Base
attr_accessible :message, :seen, :title
belongs_to :sender, class_name => "User", :inverse_of => :sent_messages
belongs_to :target, class_name => "User", :inverse_of => :recieved_messages
end
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.references :sender
t.references :target
t.string :title
t.string :message
t.boolean :seen
t.timestamps
end
end
end
我有这两个模型。当我尝试获取用户发送的消息(user.sent_messages)时,我收到如下错误:
Could not find the inverse association for sent_messages (:sender in Message)
这是我使用 Rails 的第二天,所以它可能是微不足道的,但我没有看到它。
PS:如果我从 User 类中删除 :inverse_of => :sender,user.sent_messages 可以工作,但据我所知 :inverse_of 很重要。
PPS:发现错误!在 Message 类中,我使用的是 class_name 而不是 :class_name。