Update:这都是由于一个愚蠢的错误:以前,我定义了一个与ActiveRecord创建的方法之一同名的方法,这掩盖了正确的行为并破坏了一切。我在几个小时内无法回答/结束这个问题,向所有调查过这个问题的人道歉!
我有一个令人愤怒的问题与has_many, :through =>
关系在我的Rails 3.1应用程序。
这是令人恼火的,因为在我看来,这是两个相似的关系,都是一样的。
这些关系的所有者这样声明它们:
has_many :user_skills, :dependent => :destroy
has_many :skills, :through => :user_skills
has_many :user_roles, :dependent => :destroy
has_many :roles, :through => :user_roles
has_many :conversation_users
has_many :conversations, :through => :conversation_users
(我知道我在这里没有遵循连接表的标准命名法——我只在设置好这个之后阅读了双复数、名称按字母顺序排列的约定,稍后我会重构)
前两对关系(技能和角色)工作得很好。
最后的关系(对话)没有完全工作。user.conversation_users
返回期望的数组,但user.conversations
返回nil
。不是空数组,nil
.
我可能在这里做了一些愚蠢的事情,所以我将非常感谢任何可以发现ConversationUser
或Conversation
模型错误的人。
conversation_user.rb
class ConversationUser < ActiveRecord::Base
belongs_to :user, :inverse_of => :conversation_users
belongs_to :conversation, :inverse_of => :conversation_users
validates_presence_of :user
validates_presence_of :conversation
end
conversation.rb
class Conversation < ActiveRecord::Base
has_many :messages, :dependent => :destroy
has_many :conversation_users, :dependent => :destroy
has_many :users, :through => :conversation_users
validates_presence_of :unique_id
end
(我也意识到这些还不够复杂,不足以证明has_many, :through =>
优于has_and_belongs_to_many
,但计划的附加功能将需要连接模型。)
对结语问题的回答:
这都是由于一个愚蠢的错误:以前,我定义了一个方法与ActiveRecord创建的方法之一同名,这掩盖了正确的行为,破坏了一切。