Reputation: 2357
I am iterating through a hash and displaying the values as radio buttons. The hash looks like this:
{
1=>["a", "b"],
2=>["c"],
3=>["a", "d", "f", "g"],
4=>["q"] ..
}
After selecting the values, the parameters become:
{ "commit"=>"vote", "authenticity_token"=>"db863239855c9f73b9ae54c37f6b92c858acb56f", "1"=>"a", "2"=>"c", "3"=>"d", "4"=>"q"}
How can I access these values (POST data) in the update method of the controller in order to update the count field? I have tried like this.
@votings = Voting.find(:all, :conditions => {params[:k]=>params[:val]})
@votings.each do |voting|
voting.update_attribute('vote_count',
voting.vote_count+1)
end
But gives this error:
You have a nil object when you didn't expect it! The error occurred while evaluating nil.each..
Can anybody tell where I went wrong?
Upvotes: 1
Views: 13646
Reputation: 44952
The POST
data is stored in the params
hash. So if you wanted the value of the parameter 1, you would use params[:1]
.
Now lets look at :conditions. In the find method, the :conditions
parameter can take a hash, which is what you are providing. But your code is saying, take the value of params[:k]
and set it to the value of params[:val]. But params[:k]
is nil in this example, there is no key :k
in your params hash. So when you are searching, you are getting back a nil value for @votings. Trying to use each on a nil gets you your error.
Upvotes: 4
Reputation: 664
The reason you are having serious difficulties is because you are working against the conventions baked into Rails.
Try this for size, although it will require throwing away a lot of code you have already written then wondering about the magic Rails just breathed into your application: http://railscasts.com/episodes/17-habtm-checkboxes
Upvotes: -2