Ruby on Rails: a weird no method error in my controller?
Here's what I got in my logs:
Started POST "/video_votes.437?type=up" for 127.0.0.1 at Fri Mar 18 01:11:14 -0700 2011 Processing by VideoVotesController#create as Parameters: {"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"} Com开发者_如何学编程pleted in 83ms
NoMethodError (You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]): app/controllers/video_votes_controller.rb:3:in `create'
I get this error when I click the button that calls on the create method.
Here's the code in my create method (note that line three is the @video = Video.find(params[:video_vote][:video_id])
line):
def create
@video = Video.find(params[:video_vote][:video_id])
@vote = @video.video_votes.new
if params[:type] = "up"
@vote.value = 1
else
@vote.value = -1
end
if @vote.save
respond_to do |format|
format.html { redirect_to @video }
format.js
end
else
respond_to do |format|
format.html { redirect_to @video }
format.js {render 'fail_create.js.erb'}
end
end
And here's my code for the button in my view that calls the create method:
<div id='voting_div'>
<%= button_to "+1", video_votes_path(video, :type=> "up"), :remote => true %>
<div id='vote_display'>
<p id='votes'><%= pluralize video.vote_sum, 'Votes' %></p>
</div>
<%= button_to "-1", video_votes_path(video, :type=> "down"), :remote => true %>
</div>
What's going on here? How do I fix this error?
You params hash is
{"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"}
In this hash there is no key called "video_vote" , so when you try to access params[:video_vote][:video_id]
, because params[:video_vote]
is nil. it will throw this error.
Check your routes or if you need to "GET" more values with the button, because your params hash doesn't know about the "video_vote" key.
精彩评论