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:如果我删除:inverse_of =&gt; :来自用户类的发件人,user.sent_messages有效,但据我所知:inverse_of非常重要。
PPS:发现错误!在Message类中,我使用的是class_name而不是:class_name。
答案 0 :(得分:0)
这就是我喜欢尽可能使用新风格哈希的原因
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
虽然和许多事情一样,但这通常是个人品味的问题:)