Create or update multiple records at a time using strong options in Rails 4

I have two questions:


In Rails 3, you can update multiple records using

Product.update(params[:products].keys, params[:products].values)

How do you do the same in Rails 4 using strong parameters? How to create several records at the same time? Could you offer your solution with an example in the following format:

params = ActionController::Parameters.new(...)
Product.create!(params.require(...)permit(...)

In addition, my product model has a column with a number that equals the order in which they were updated. Is there any way to pass counter value during update?

Thanks.

+4
source share
2 answers

Perhaps you are thinking about using nested_attributes? It will look something like this:

params.require(:parent_model).permit(
  :id,
  child_models_attributes: [
    :id,
    :parent_model_id,
    :child_model_attribute_1,
    :child_model_attribute_2
  ]
)

from

params = {
  id: parent_model.id,
  child_models_attributes: {
    '0' => {
      id: child_model_1.id,
      parent_model_id: parent_model.id,
      child_model_attribute_1: 'value 1',
      child_model_attribute_2: 12312
    }
  }
}

_ , :

class ChildModel < Activerecord::Base
  belongs_to :parent_model
end

class ParentModel < Activerecord::Base
  has_many :child_models
  accepts_nested_attributes_for :child_models
end
0

accepts_nested_attributes_for

SO, , , , , , nested_attributes . , , , :

product_params = params.require(:products).permit(product_fields: [:value1, :value2, etc...])

, , field_for product_fields ( any_name):

form_for :products do |f|
  f.fields_for product_fields[] do |pf|
    pf.select :value1
    pf.select :value2
    ...
  end
end

()

product_fields => {0 => {value1: 'value', value2: 'value'}}

/

0 => {value1: 'value', value2: 'value'}, 1 => {value1: 'value', value2: 'value'}, etc...

:

.permit(0 => [value1: 'value', value2: 'value'], 1 => [...], 2 => [...], ad infinitum)

, . Rails 4.2, . : Rails?.

, :

product_params[:product_fields].keys.each_index do |index|
  Product.create!(product_params.merge(counter: index))
end

, , , .: -)

0

All Articles