问题
I have request model and nested model filled_cartridges when I create new request object i also need to set the values of nested params inside create controller method. I have many nested params so i need to iterate through them, something like that:
params[:request][:filled_cartridges_attributes].each do |_,value|
# here i try to set :client_id parameter, which is nested
# where @client.id is defined
value[:client_id] = @client.id # i am pretty sure that the problem is here
# is it a correct way of ding that?
end
EDIT:
has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
accepts_nested_attributes_for :filled_cartridges, reject_if: proc { |attributes| attributes['title'].blank? },allow_destroy: true
and my nested model:
create_table :filled_cartridges do |t|
t.integer :client_id, null: false
t.string :cartridge_name, null: false
t.integer :cartridge_id, null: false
t.integer :request_id, null: false
t.integer :count, default: 1
t.datetime :fill_date
t.timestamps null: false
end
here client_id,request_id and cartridge_id are all should should be set inside controller. And my strong params:
def request_params
params.require(:request).permit(:name, :address, :phone, :mobile,:date,
:filled_cartridges_attributes => [:client_id,:cartridge_name,:cartridge_id,
:request_id,:count,:fill_date,:_destroy,:id],
end
来源:https://stackoverflow.com/questions/29901150/how-to-set-values-of-nested-parameters-in-rails-4-from-controller-method