简体   繁体   English

如何在 Rails 上的 Ruby 中以正确的方式将参数从视图传递到 controller

[英]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.我有一段时间使用 Rails,但我遇到了问题,不知道如何解决。

There is a model X and a model YW and between them a joint model有一个 model X 和一个 model YW ,它们之间有一个接头 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.我需要从视图传递到 controller 作为 X_yw_attributes 参数的一部分,但我不知道如何在 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您可以查看更详细的文档accept_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?从您的问题中,我无法判断您要将信息存储在哪里,在 YW 或联合表中?
If you want to store data in YW, you can set accepts_nested_attributes_for:yw first, and then pass yw_attributes to controller.如果要在YW中存储数据,可以先设置accepts_nested_attributes_for:yw ,然后将yw_attributes传递给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.您编写的代码看起来像是在 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.如果您想这样做,请将:id 添加到 x_yw_attributes 以表明您想要更新而不是创建它们。

You can also check nested_form gem by Ryan B. which he combines some javascript code to make the life easier您还可以查看 Ryan B 的nested_form gem ,他结合了一些 javascript 代码,让生活更轻松

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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