我對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