我有兩個型號發佈一個數組到數據庫中軌
文章
class Article < ActiveRecord::Base
mount_uploader :photo, ImageUploader
has_many :comments
has_many :article_tags
has_many :tags, :through => :article_tags
belongs_to :category
validates :title, presence: true
validates :text, presence: true
end
ArticleTag
class ArticleTag < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end
標籤
class Tag < ActiveRecord::Base
has_many :article_tags
has_many :articles, :through => :article_tags
end
我這是怎麼得到的標籤在裏面 。
@article = params[:article]
@tags = params[:tag_ids]
現在真正的問題是與張貼文章到文章表以及張貼的各種物品進入article_tags表相關聯的標籤。
更新
我使用simple_form_for寶石,讓我用聯想的方法,所以這個問題沒有得到標記爲形式而只是將它們張貼到數據庫中引導創建一個多選(創建新article_tags的行)。我希望能夠通過@article.article_tags
檢索它們。這就是嘗試,但我不知道它是否正確。
@article_params = params[:article]
article_params[:tag_ids].each do |tag|
@article_tag = @article.article_tags.build('article_id'=>@article.id,'tag_id'=>tag)
@article_tag.save
end
def article_params
params.require(:article).permit(:title,:category_id,:text, :photo,:tag_ids => [])
end
這與正在創建的文章這就像在IE中的文章和article_tags表同樣的方法在同一時間發佈到兩個表來完成。
更新了問題 – christoandrew