简体   繁体   English

如何在Rails控制器参数中遍历属性

[英]How to loop through attributes in rails controller params

I have a has_many relationship and I want to loop a certain field on each of the items link to the main model (ingredients on a recipe). 我有一个has_many关系,我想在每个链接到主模型的项目上循环某个字段(配方上的成分)。 Im trying to do this in before_filter so I can parse the users input correctly into what I want. 我试图在before_filter中做到这一点,以便我可以正确地将用户输入解析为我想要的内容。 How can I set up the do loop to get the params I want 我该如何设置do循环来获取我想要的参数

The request parameters in Rails are accessible via the params hash. 可通过params哈希访问Rails中的请求参数。 You can loop over the hash using an iterator. 您可以使用迭代器遍历哈希。

params.each do |k,v|
  puts "#{k}: #{v}"
end

As for parsing the user's input, I personally would not do that in a before_filter method. 至于解析用户的输入,我个人不会在before_filter方法中这样做。 You gave an example below of converting input such as "1 1/2" to 1.5. 您在下面给出了将“ 1 1/2”之类的输入转换为1.5的示例。 Try something like this: 尝试这样的事情:

ingredient.rb: Ingredient.rb:

# amount :decimal (assuming this column exists on the ingredients table)

def humanized_amount
  amount.humanize!
end    

def humanized_amount=(value)
  amount = cast_humanized_value_to_decimal(value)
end

Then use humanized_amount as the attribute for your form input. 然后将humanized_amount用作表单输入的属性。 Just a suggestion. 只是一个建议。 There's not really a right answer. 确实没有正确的答案。

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

相关问题 如何在ajax中传递可以通过Rails中的ruby控制器中的参数访问的属性? - How to pass the attributes in ajax which can be accessed through params in the controller in ruby on rails? 如何在控制器中的Rails参数中添加属性并传递给其他控制器 - How to add attributes to rails params in a controller and pass to different controller Rails params属性-使用控制器中的params字段 - Rails params attributes - using the params fields in the controller Rails控制器调用嵌套属性的参数 - rails controller invoking params of nested attributes 如何修改rails控制器中的参数 - How to modify the params in rails controller Rails循环遍历params数组并保存记录 - Rails loop through params array and save records 如何使用Rails Action Controller嵌套参数来允许特定属性哈希 - How to use Rails Action Controller Nested Params to Permit a Specific Attributes Hash 如何在控制器中循环一些嵌套参数? 导轨3 - How do I loop through some nested parameters in the controller? Rails 3 Rails以表格形式遍历所需的属性 - rails loop through required attributes in a form 我们如何通过 rails 中的 controller 操作将任何参数 [:file] 传递给 Sidekiq Worker - How can we pass any params[:file] to Sidekiq Worker through controller action in rails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM