Rails 3 - How to create a new post from link_to

I am trying to create a "tag" functionality that allows the user to "tag" the elements in which they are interested. Here is my model

class tag belongs_to :user belongs_to :item end 

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

In the :items list :items I need a link next to each :item , which allows the user to mark :item . Since I know :user_id and :item_id , I want to create a new entry :tag , set the id fields and save the entry - all without user intervention. I tried the following link_to call, but the record is not 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 inside the statement: @item.each do |item| , 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 entry in the database. Here is my action :create in 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 entry?

+8
ruby-on-rails-3 link-to belongs-to
source share
1 answer

The fact that the generated URL has a method as a parameter means that it performs a GET, not a POST.

The signature you should use 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" %> 

: The method should be passed in html_options and left in url_options. That should work.

+14
source share

All Articles