简体   繁体   中英

How to implement controller in order to handle the creation of one or more than one record?

I am using Ruby on Rails 4.1. I have a "nested" model and in its controller I would like to make the RESTful create action to handle cases when one or more than one records are submitted. That is, my controller create action is:

def create
  @nester = Nester.find(:nester_id)
  @nesters_nested_objects = @nester.nested_objects.build(create_params)

  if @nnesters_ested_objects.save
    # ...
  else
    # ...
  end
end

def create_params
  params.require(:nesters_nested_object).permit(:attr_one, :attr_two, :attr_three)
end

I would like it to handle both cases when params contain data related to one object and when it contains data related to more than one object.

How can I make that? Should I implement a new controller action (maybe called create_multiple ) or what? There is a common practice in order to handling these cases?

Well, if you insist on creating those records aside from their nest, I can propose to go with something like this (it better be a separate method really):

def create_multiple
  @nest = Nester.find(params[:nester])
  params[:nested_objects].each do |item|
    @nest.nested.new(item.permit(:attr_one, :attr_two, :attr_three))
  end
  if @nest.save
     ....
  else
     ....
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM