开发者_StackOverflow中文版I am trying to allow for voting on posts in a Ruby on Rails blog that I created. I don't really want to go the plugin or gem route because I think I am close. Here is the situation:
I am displaying all my posts in /posts/index.html.erb through the partial _post.html.erb. With each post I am rendering the following code for the vote button:
<% remote_form_for [@post, Vote.new] do |f| %>
<%= f.hidden_field :ip_address, :value => "#{request.remote_ip}" %>
<%= submit_tag 'Me Too', :class => 'voteup' %>
<% end %>
Which sends the request through the votes controller:
def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create!(params[:vote])
respond_to do |format|
format.html { redirect_to @posts}
format.js
end
end
The error I am getting is Couldn't find Post without an ID
which makes sense because I am not on the /posts/show.html.erb page.
Is there a way that I can pass the post_id to the votes_controller (and into the post_id column in the votes table) from the /posts/index.html.erb view?
Try adding this in the view, after the remote_form_for
:
<%= f.hidden_field :post_id, :value => @post.id %>
You might also need to to this in the def create
@post = Post.find(params[:vote][:post_id]) #note the added [:vote]
If you look at the params after those changes, it should show:
{"vote"=>{"ip_address"=>"127.0.0.1", "post_id"=> >>actual-post-id-here<< },
"commit"=>"Vote Up ↑" ..........
Also, I recommend having a look at the excellent RailsCasts by Ryan Bates. Lots of great video tutorials there.
精彩评论