我对ROR相当陌生,所以我现在被这个问题困住了。Ruby on Rails:协会
我正在设置一个包含文章和模板的应用程序。 我想用许多文章创建模板,并且可以将相同的文章分配给多个不同的模板。 所以,当你创建一个模板,我想分配文章。你会认为直接使用has_many关联,但我不认为这抓住了我的问题。
我想分配文章到多个模板,所以我认为使用某种链接表将在这里的地方。
但我不知道如何在轨道中做到这一点!或者我应该寻找什么样的解决方案。
有没有人能告诉我这个问题?
我对ROR相当陌生,所以我现在被这个问题困住了。Ruby on Rails:协会
我正在设置一个包含文章和模板的应用程序。 我想用许多文章创建模板,并且可以将相同的文章分配给多个不同的模板。 所以,当你创建一个模板,我想分配文章。你会认为直接使用has_many关联,但我不认为这抓住了我的问题。
我想分配文章到多个模板,所以我认为使用某种链接表将在这里的地方。
但我不知道如何在轨道中做到这一点!或者我应该寻找什么样的解决方案。
有没有人能告诉我这个问题?
您是否在寻找has_and_belongs_to_many
的关联?
http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association
本质上检查出的东西,去到控制台,然后输入
$轨G型文章的标题:绳体:文字
$轨g模型模板名称:字符串some_other_attributes:类型等等
$轨摹迁移create_articles_templates
然后编辑create_articles_templates:
class CreateArticlesTemplates < ActiveRecord::Migration
def up
create_table :articles_templates, :id => false do |t|
t.integer :template_id, :article_id
end
end
def down
end
end
您可以创建链接模型articles_template
rails generate model articles_template
一起文章,模板
class CreateArticlesTemplates < ActiveRecord::Migration
def change
create_table :articles_templates do |t|
t.references :article
t.references :template
t.timestamps
end
end
end
引用
,然后设置的关联模型articles_template
class ArticlesTemplate < ActiveRecord::Base
belongs_to :article
belongs_to :template
end
class Article < ActiveRecord::Base
has_many :articles_templates
has_many :templates, :through => :articles_templates
end
class Template < ActiveRecord::Base
has_many :articles_templates
has_many :articles, :through => articles_templates
end
恕我直言,这是最好的做法,因为你可以添加一些额外的功能,对入联模式和表。 (更多关于这个here)
这也是一个非常好的解决方案的问题。最后,这取决于你是否需要与两个模型的连接关联一些状态。 – 2012-04-29 10:32:05