简体   繁体   中英

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). Im trying to do this in before_filter so I can parse the users input correctly into what I want. How can I set up the do loop to get the params I want

The request parameters in Rails are accessible via the params hash. 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. You gave an example below of converting input such as "1 1/2" to 1.5. Try something like this:

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. Just a suggestion. There's not really a right answer.

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