Adding name value with link_to
I'm using a link_to
to create an object in my Rails 3 app. Searching has given me the proper way to use link_to
with the :post
method, but I'm wondering if using link_to
to pass in a name value for my object as well. Here is my link:
<%= link_to "Todo text", {:controller => "profiles", :action => "create_inside", :method => :post}, :class => "button white" %>
My profiles_controller.rb
:
def create_inside
@todo = Insidetodo.new
@todo.save!
if @todo.save
redirect_to @profile.todo, :notice => 'Todo successfully added.'
else
render :action => 'new'
end
end
My todo.rb
model:
class Todo < ActiveRecord::Base
has_and_belongs_to_many :profiles
validates :name, :presence => true
end
Is there a way to add in :name => "#{@user.profile.todotext}"
to the link_to
so that it passes and saves? I don't开发者_如何学JAVA know if it's creating properly because at the moment when I click a link_to
I get a validation error - Validation failed: Name can't be blank
.
For passing name
in the link_to
<%= link_to "Todo text", {:controller => "profiles", :action => "create_inside", :name => "#{@user.profile.todotext}", :method => :post}, :class => "button white" %>
and the controller must be
def create_inside
@todo = Insidetodo.new(:name => params[:name])
if @todo.save
redirect_to @todo.goal, :notice => 'Todo successfully added.'
else
render :action => 'new'
end
end
But the link_to
will pass the name parameter in url only(like <a href="/profiles/create_inside?name=xxx">Todo text</a>
).
If you want the name not to be sent in the url, you might want to use a form and use a submit button instead of the link as it is representing an action and not a link.
<%= form_tag(:controller => "profile", :action => "create_profile") do -%>
<%= hidden_field_tag :name, @user.profile.todotext %>
<%= submit_tag "Todo Text" %>
<% end -%>
精彩评论