0

我需要一行代碼來生成has_and_belongs_to_many連接表,否則我將返回Django以獲取其更簡單的多對多結構。Rails 3 HABTM單線程

軌道3生成模式article_tags [..]

Models 

# article.rb 
has_many :articles_tags 
has_many :tags, :through => :articles_tags 

# tag.rb 
has_many :articles_tags 
has_many :articles, :through => :articles_tags 

# article_tag.rb 
belongs_to :tag 
belongs_to :article 

回答

3

喔等待哈哈,我覺得這可能做的伎倆:

rails g model articles_tags article:references tag:references --no-id --no-timestamps 

我想知道是否有禁止模型文件的創建(article_tags.rb),這樣我就可以使用標準的has_and_belongs_to_many語法而不必指定:through param?我正在尋找最終的單行代碼:任何人都可以改進上述單行代碼以使僅使用has_and_belongs_to_many語法,而無需加入模型!否則,我要回到Django,它內置了ManyToManyFields。

2

這聽起來像你正在尋找的標準has_and_belongs_to_many:

# article.rb 
has_and_belongs_to_many :tags 

# tag.rb 
has_and_belongs_to_many :articles 

你的連接表將被稱爲articles_tags,和只需要包含兩列,即article_idtag_id(不需要id列,因爲它不是模型)。

這是在Rails Guide to Associations。我強烈建議熟悉Rails指南。

這對發電機來說簡直太簡單了。所有你需要的是兩個空模型類和連接表,這將在遷移進行定義,像這樣:

def self.up 
    create_table :articles_tags, :id => false do |t| 
    t.integer :article_id 
    t.integer :tag_id 
    end 
end 

def self.down 
    drop_table :articles_tags 
end