【发布时间】:2011-10-21 18:41:36
【问题描述】:
更新:这完全是由于一个愚蠢的错误:以前,我定义了一个与 ActiveRecord 创建的方法之一同名的方法,它掩盖了正确的行为并破坏了一切。再过几个小时我都无法回答/结束这个问题,向任何调查过这个问题的人道歉!
我的 Rails 3.1 应用程序中的 has_many, :through => 关系存在一个令人恼火的问题。
这很令人生气,因为据我所知,它与两个都有效的相似关系相同。
这些关系的所有者这样声明它们:
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,但计划中的附加功能将需要连接模型。)
【问题讨论】:
标签: ruby-on-rails-3.1 has-many-through