Rails 3 - How do you create a new record from link_to
Asked Answered
S

1

8

I'm trying to create a 'tag' functionality which allows a user to "tag" items in which they are interested. Here is my model

class tag
  belongs_to :user
  belongs_to :item
end

The corresponding DB table has the necessary :user_id and :item_id fields.

In the list of :items I want a link next to each :item that allows the user to tag the :item. Since I know the :user_id and the :item_id, I want to create a new :tag record, set the id fields, and save the record - all with no user intervention. I tried the following call to link_to , but no record is saved in the database:

<%= link_to 'Tag it!', {:controller => "tracks", 
                       :method => :post, 
                       :action => "create"},
                       :user_id => current_user.id, 
                       :item_id => item.id %>

(This code is within an: @item.each do |item| statement, so item.id is valid.)

This link_to call creates this URL:

http://localhost:3000/tags?method=post&tag_id=7&user_id=1

Which does not create a Tag record in the database. Here is my :create action in the tags_controller

 def create
    @tag = Tag.new
    @tag.user_id = params[:user_id]
    @tag.tag_id = params[:tag_id]
    @tag.save
  end

How can I get link_to to create and save a new tag record?

Shephard answered 28/8, 2011 at 3:46 Comment(0)
R
14

The very fact that the generated URL has method as parameter implies it's doing a GET and not POST.

The link_to signature you must be using is link_to(body, url_options = {}, html_options = {})

<%= link_to 'Tag it!', {:controller => "item", 
                       :action => "create", 
                       :user_id => current_user.id, 
                       :item_id => item.id},
                       :method => "post" %>

:method should be passed to html_options and rest to url_options. This should work.

Repute answered 28/8, 2011 at 6:10 Comment(3)
Thanks! It works great with your fix. Showing the link_to signature in your answer really helped me finally understand what was going on. Much appreciated.Shephard
Just a quick comment. In the url_options hash the controller key's value should be "items" not "item". It would give you an ActionController routing error when trying to display the link.Collado
@dexter, what happens if the link is outside of the app, like in an email, for example? My use case is for RSVPs. I want to create a new RSVP directly from the email link, but I want to stay RESTful.Geyer

© 2022 - 2024 — McMap. All rights reserved.