2016-01-21 68 views
1

我有兩個型號發佈一個數組到數據庫中軌

文章

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表同樣的方法在同一時間發佈到兩個表來完成。

回答

0

你有兩個選擇:

  1. 如果要關聯現有tagsarticle,你只需要填充tag_ids
  2. 如果你想創建tags,你」將不得不使用accepts_nested_attributes_for

現有標籤

添加現有標記的文章很簡單:

#app/models/article.rb 
class Article < ActiveRecord::Base 
    has_many :article_tags 
    has_many :tags, through: :article_tags 

    validates :title, :text, presence: true #-> declare multiple validations on same line 
end 

#app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController 
    def create 
     @article = Article.new article_params 
     @article.save 
    end 

    private 

    def article_params 
     params.require(:article).permit(tag_ids: []) 
    end 
end 

使用collection_singular_ids屬性分配在父「加盟」記載:

#app/views/articles/new.html.erb 
<%= form_for @article do |f| %> 
    <%= f.collection_select :tag_ids, Tag.all, :id, :name %> 
    <%= f.submit %> 
<% end %> 

這將撥出任何tag到您的新article,但是,它會而不是允許您創建新標籤。


新標籤

如果你希望你的article創建新的標籤,你將不得不使用accepts_nested_attributes_forfields_for

#app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController 
    def new 
    @article = Article.new 
    @article.tags.build 
    end 

    def create 
    @article = Article.new article_params 
    @article.save 
    end 

    private 

    def article_params 
    params.require(:article).permit(tags_attributes: [:name]) 
    end 
end 

#app/views/articles/new.html.erb 
<%= form_for @article do |f| %> 
    <%= f.fields_for :tags do |t| %> 
     <%= t.text_field :name %> 
    <% end %> 
    <%= f.submit %> 
<% end %> 

這將自動創建新的標籤將它們與您的新article關聯。

+0

更新了問題 – christoandrew