[英]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.