views:

12

answers:

1

G'day all.

In a Rails app I have 2 models: users and spots, with a habtm relationship and join table. In the spot/show action I can create a form to ask the current user if they have visited this current spot (checkbox) and click save to create a record in the join table.

This works well (so I know my models and relationships are all good) however is not that elegant. Is there a way to do this without having to use a checkbox and submit button? Preferably with just a button?

My research suggests the rails button_to might do it, but I can't find a working example.

Many thanks.

+2  A: 

Yes, button_to will work fine:

<%= button_to "I've visited here", {:action => "visited", :id => @spot} %>

Will generate a button that when pressed will pass in the @spot in the params as expected. You can then (assuming you have a current_user method because you're using a standard user model framework), do something like this:

def visited
  spot = Spot.find(params[:id])
  current_user.spots << spot
  redirect_to :action => "show", :id => spot
end

Hope that helps.

p7r
Thanks vagueware. That worked. I initially got a no route matches error, but updated the routes.rb file, added a flash message to say the spot has been added, and it works well.
Ray
@Ray, if this answer is the solution you should rewards @vagueware by accepting his answer
jigfox
@Ray - ah, yes, sorry, the routes.rb file will need a quick update, you're right. Apologies...
p7r