我有请求模型和嵌套模型filled_cartridges 当我创建新的请求对象时,我还需要在create controller方法中设置嵌套params的值。我有很多嵌套的params,所以我需要遍历它们,类似的东西:
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
编辑:
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

和我的嵌套模型:
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

这里应该在控制器内部设置client_id,request_id和cartridge_id。 还有我强大的参数:
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