2013-10-02 46 views
3

我在軌道上4.我有三個模型,Blends,Addons和AddonPairings。用戶可以創建共混物和如何通過has_many關係通過控制器提交collection_check_box?

Blend 
    have_many :addon_pairings 
    have_many :addons, through: :addon_pairings 

Addon 
    have_many :addon_pairings 
    have_many :blends, through: :addon_pairings 

AddonPairing 
    belong_to :blend 
    belong_to :addon 

我的插件是在數據庫中的所有預製供用戶選擇儘可能多的,因爲他們要附加到一個融合。

在我new.html.erb我的共混物

<%= form_for [current_user, @blend] do |f| %> 

    <div class="form-group"> 
     <%= f.label :addons, "Add some addons to your blend" %> 
     <%= f.collection_check_boxes :addon_ids, Addon.all, :id, :name %> 
    </div> 

    <div class="form-group"> 
     <%= f.submit class: "btn btn-lg btn-primary" %> 
    </div> 
<% end %> 

我的混合控制器

def create 
    @user = User.find(params[:user_id]) 
    @blend = @user.blends.build(blend_params) 
    if @blend.save 
     redirect_to @user, notice: "Your blend has been created." 
    else 
     flash.now[:notice] = "Something went wrong. Please check the errors below." 
     render 'new' 
    end 
    end 
private 

def blend_params 
     params.require(:blend).permit(:name, :addon_ids) 
    end 

如何讓我的控制器創建我的addon_pairings表連接的共混物,所選擇的插件的記錄?謝謝。

回答

1

你已經實施了某種糟糕的事情。

你需要使用'accepting_nested_pa​​rameters'來做到這一點。

這樣,你將使用fields_for標籤來創建一個'表單中的表單',它實際上在另一個模型中創建了這個字段,使得這個條目擁有當前觸發控制器並生成主表單的對象。所以,既然你collection_check_box創建由當前擁有的對象,但在另一種模式,它需要像塊(只是一個例子)內:

<%= fields_for @owner.belonged_name %> 
<%= collection_check_box %> 
<% end %> 

我建議你railscasts.com/episodes/196- nested-model-form-part-1和這個鏈接(http://www.createdbypete.com/articles/working-with-nested-forms-and-a-many-to-many-association-in-rails-4/)來理解關於嵌套參數的哲學。

請注意,您必須允許您的控制器上的屬性,因爲attr_params已棄用。

希望它有幫助。

0

在blend_params方法只是改變

params.require(:blend).permit(:name, :addon_ids) 

params.require(:blend).permit(:name, addon_ids: [])