【发布时间】:2016-02-23 08:11:44
【问题描述】:
我正在练习 Rails。我想为他们提供消息和标签(单个消息应该有很多标签,单个标签应该有很多消息)。我有 2 个相关模型:Messages 和 Tags。它们使用 has_and_belongs_to_many 关联。我正在使用ffaker 来填充表格
型号:
消息:
class Message < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_and_belongs_to_many :tags
end
标签:
class Tag < ActiveRecord::Base
has_and_belongs_to_many :messages
end
迁移:
消息:
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.text :content
t.timestamps
end
end
end
标签:
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :title
end
end
end
加入表:
class CreateMessagesTagsJoinTable < ActiveRecord::Migration
def change
create_table :messages_tags, id: false do |t|
t.references :tag, index: true
t.references :message, index: true
end
end
end
种子文件:
5.times { Message.create([content: FFaker::CheesyLingo.paragraph]) }
Message.all.each do |msg|
rand(4).times { Comment.create([content: FFaker::CheesyLingo.sentence, message_id: msg.id]) }
2.times { msg.tags.create([title: FFaker::HipsterIpsum.word.gsub(' ','-').downcase]) }
end
评论无关紧要。所以首先我在这里填充消息表。其次,我从消息内部填充标签表。我最终得到的是填充消息和标签表,其中每条消息都有 2 个标签。
现在,问题来了:
如何将已创建的标签与消息相关联,反之亦然?我知道如何通过创建它们来做到这一点,但现在我想将几个标签关联到单个消息。我还想将一些消息与单个已创建的标签相关联。 怎么做,语法是什么?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 seeding