简体   繁体   中英

How to pass parameters in correct way from view to controller in Ruby on Rails

I've some time working with Rails but I have a problem and don't know how to solve.

There is a model X and a model YW and between them a joint model

I need to pass from view to controller as part of the parameters the X the x_yw_attributes but I don't know how stablish the correct way of the attribute name in html.

The idea will be this:

"x" => {
"name"=>"Name 1", "description"=>"Descripción 1", "status"=>"true",
"x_yw_attributes" =>[
            {"yw_id"=>"15", "range"=>"[1,2,3,5]", "payment" => "[2,3,4,5,6,7]"},  
            {"yw_id"=>"17", "range"=>"[1000,2000,3000,5000]", "payment" => "[20,30,40,50,60,70]"},
            {"yw_id"=>"19", "range"=>"[10000,20000,30000,50000]", "payment" => "[200,300,400,500,600,700]"}
           ], 
"categories_ids"=>["", "2", "", "5", "5"]
}

I know how to do it with the categories for example:

<input type="checkbox" name="x[category_ids][]" value="2" checked="checked">
<label for="category_2">Category 2</label>

So let me know how should I write the name attribute or I you need more info. Thaks for the help.

You can check the document with more detail accepts_nested_attributes_for
And from your question I can't tell where do you want to store the information, in YW or the joint table?
If you want to store data in YW, you can set accepts_nested_attributes_for:yw first, and then pass yw_attributes to controller.
The strong parameters would be something like:

def x_params
  params.requires(:x).permit(:name, :description, :status, yw_attributes: [:id, :range, :payment, :_destroy])
end

The code you wrote looks like to store information in the join_table. If that's you want to do, add:id into x_yw_attributes to indicate that you want update rather than create them.

You can also check nested_form gem by Ryan B. which he combines some javascript code to make the life easier

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