VPNTIME
VPNTIME

Reputation: 761

Why is the Photo Id not being passed to create action?

I'm implementing likes for photos, and the id isn't being passed. I don't know why. Could someone please explain why? I feel it would help me understand rails better.

I get this error, after clicking like: "Couldn't find Photo without an ID"

On the photo show page I have this:

<%= form_for(@photolike, :url => {:controller => :photolikes, :action => 'create'}) do |f| %>
<%= f.hidden_field :photo_id, :value => @photo.id %> 
<%= f.submit "like", class: "btn postbtn right" %>
<% end %>

this is the controller for photos

def show
if user_signed_in?
 @comment = current_user.sent_photocoments.new(params[:photo_comment])
 end
 @photo = Photo.find(params[:id])
 @photolike = Photolike.new
end

And in the photolikes controller, I have this:

def create
 @photo = Photo.find(params[:id])
 @photolike = Photolike.new(:photo_id => @photo.id, :user_id => current_user.id)
 @photolike.addlike
 @photolike.save
 redirect_to @photo
end

Upvotes: 0

Views: 50

Answers (2)

12321
12321

Reputation: 36

def create
 @photo = Photo.find(params[:photolike][:photo_id])
 @photolike = Photolike.new(:photo_id => @photo.id, :user_id => current_user.id)
 @photolike.addlike
 @photolike.save
 redirect_to @photo
end

Upvotes: 1

lurker
lurker

Reputation: 58244

Your submit is submitting the photo_id labeled as photo_id (in your hidden field). So your controller needs to retrieve it via params[:photo_id] rather than params[:id].

Upvotes: 0

Related Questions