DRing
DRing

Reputation: 7039

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

Upvotes: 0

Views: 1684

Answers (1)

Stephen Kiningham
Stephen Kiningham

Reputation: 504

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.

Upvotes: 2

Related Questions