Rails - has_many through:添加到集合时设置连接模型外键?

时间:2018-02-17 17:30:30

标签: ruby-on-rails activerecord

我有这些联想:

character.rb

has_many :messagechats, dependent: :destroy
has_many :messageconversations, through: :messagechats, source: :conversation

messagechat.rb

belongs_to :character
belongs_to :conversation, class_name: 'Messageconversation', foreign_key: 'conversation_id'

messageconversation.rb

has_many :chats, class_name: 'Messagechat', dependent: :destroy
has_many :characters, through: :chats, source: :character

数据库中的Messagechat模型确实有conversation_id列,而不是messageconversation_id列。

我正在尝试将character添加到@messageconversation,其中包含:

@messageconversation.characters << character

但是这会引发这个错误:

ActiveModel::UnknownAttributeError (unknown attribute 'messageconversation_id' for Messagechat.)

因为<<假定联接模型中的foreign_key将来自messageconversation(即messageconversation_id)。我需要foreign_keyconversation_id。使用foreign_key设置<<的正确语法是什么?还是有另一种方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

首先,我认为你应该修改你的文件和类名来表示空格,即message_conversation.rbclass MessageConversation/:message_conversation

您应该能够指定定义关联的外键。请参阅foreign_key options的导轨指南。

更新:我用您的模型制作了一个新的应用程序,希望它有助于说明。

class MessageChat < ApplicationRecord
  belongs_to :character
  belongs_to :conversation, class_name: 'MessageConversation'
end

class MessageConversation < ApplicationRecord
  has_many :chats,
           class_name: 'MessageChat',
           dependent: :destroy,
           foreign_key: :conversation_id
  has_many :characters, through: :chats
end

class Character < ApplicationRecord
  has_many :message_chats, dependent: :destroy
  has_many :message_conversations, through: :message_chats, source: :conversation
end

这有你正在寻找的所有协会(据我所知)工作。

irb(main):002:0> conversation = MessageConversation.create
=> #<MessageConversation id: 5>
irb(main):003:0> character = Character.create
=> #<Character id: 5>
irb(main):004:0> conversation.characters << character
=> #<ActiveRecord::Associations::CollectionProxy [#<Character id: 5>]>
irb(main):005:0> character.message_chats
=> #<ActiveRecord::Associations::CollectionProxy [#<MessageChat id: 2, character_id: 5, conversation_id: 5>]>