上下文如下,我有可以有多個角色的實體。這些角色可由用戶管理。如何在嵌套表單中處理強參數? Rails 4
例如,名爲「Lipsum」的實體可能是「收銀員和銷售員」。所以,這是一個關係many_to_many。
所以,我有我的3種型號:實體,type_entity和entity_by_type
class Entity < ActiveRecord::Base
has_many :entity_by_types
has_many :type_entities, :through => :entity_by_types
accepts_nested_attributes_for :entity_by_types
end
class EntityByType < ActiveRecord::Base
belongs_to :entity
belongs_to :type_entity
end
class TypeEntity < ActiveRecord::Base
has_many :entity_by_types
has_many :entities, :through => :entity_by_types
end
我有實體類型普通CRUD。
現在,在實體的CRUD中,我有一個字段Select-Option Multiple。用戶選擇的其中一種或多種類型,即正在創建的實體。
然後我控制器實體如下:
class Logistics::EntitiesController < ApplicationController
def index
@type_entities = TypeEntity.all
render layout: false
# I use this for show All entities by TypeEntity in my view index
end
def show
end
def new
@type_entities = TypeEntity.all
@entity = Entity.new
render layout: false
end
def create
entity = Entity.new(entity_parameters)
if entity.save
flash[:notice] = "Succesfull!."
redirect_to :action => :index
else
flash[:error] = "Error."
redirect_to :action => :index
end
end
def edit
@entity = Entity.find(params[:id])
@type_entities = TypeEntity.all
@action = 'edit'
render layout: false
end
def update
entity = Entity.find(params[:id])
entity.update_attributes(entity_parameters)
flash[:notice] = "Succesfull."
redirect_to :action => :index
end
def destroy
@entity = Entity.destroy(params[:id])
render :json => @entity
end
private
def entity_parameters
params.require(:entity).permit(:name, :surname, entity_by_types_attributes: [:id, :entity_id, :type_entity_id])
end
end
而我的部分形式(方法創建和更新)是:
= simple_form_for([:namespace, @entity], html: {class: 'form-horizontal' }) do |f|
= f.input :name, placeholder: "Nombre", input_html: { class: 'form-control' }, label: false
= f.input :surname, placeholder: "Apellidos", input_html: { class: 'form-control' }, label: false
%select.select2#type-entity-select{:name => "entity[entity_by_types_attributes][type_entity_id][]", :style => "width:100%;padding: 0;border: none;", :multiple => true}
- @type_entities.each do |tent|
%option{value: "#{tent.id}"}
= tent.name
但是,當我在按鈕點擊提交,並且「 「type_entity_id」有1個或更多值;在我的數據庫中只顯示1條記錄,其中entity_id正常,但type_entity_id爲NULL。
此外只查看1條記錄,何時應該看1條或多條記錄,具體取決於表單中選擇的類型數量。
這裏的問題是以數組的形式通過type_entity_id的方式。那麼,我該怎麼做呢?
PD
以下是PARAMS如何去我的控制器:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ASD"1231+Dssr6mRJcXKh9xHDvuVDmVl4jnwIilRBsuE=", "entity"=>{"name"=>"Lorem", "surname"=>"Ipsum", "entity_by_types_attributes"=>{"type_entity_id"=>["1", "4"]}}}
我得到錯誤500:'TypeError(沒有將字符串隱式轉換爲整數)'。我用更多的信息更新了我的問題。 – Dvex
您可以從您的控制器添加創建或更新的定義嗎? –
好的,已經添加 – Dvex