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

岁酱吖の 提交于 2019-12-06 23:49:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7218940/rails-3-how-do-you-create-a-new-record-from-link-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!