Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 658
Don Leatham Avatar asked Aug 28 '11 03:08

Don Leatham


People also ask

How does Link_to work in Rails?

Rails is able to map any object that you pass into link_to by its model. It actually has nothing to do with the view that you use it in. It knows that an instance of the Profile class should map to the /profiles/:id path when generating a URL.


1 Answers

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.

like image 54
dexter Avatar answered Sep 23 '22 14:09

dexter