问题
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