2011-10-16 31 views
1

我正在使用link_to在我的Rails 3应用程序中创建对象。搜索给了我正确的方法来使用link_to:post方法,但我想知道是否使用link_to也为我的对象传入名称值。这里是我的链接:使用link_to添加名称值

<%= link_to "Todo text", {:controller => "profiles", :action => "create_inside", :method => :post}, :class => "button white" %> 

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 

todo.rb型号:

class Todo < ActiveRecord::Base 
    has_and_belongs_to_many :profiles 
    validates :name, :presence => true 
end 

有没有办法在:name => "#{@user.profile.todotext}"添加到link_to使它通过并保存?我不知道它是否正确创建,因为当我点击link_to时,出现验证错误 - Validation failed: Name can't be blank

回答

1

对于在link_to

<%= link_to "Todo text", {:controller => "profiles", :action => "create_inside", :name => "#{@user.profile.todotext}", :method => :post}, :class => "button white" %> 

并通过name控制器必须

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 

link_to将只传递URL名称参数(如<a href="/profiles/create_inside?name=xxx">Todo text</a>)。

如果您不想在url中发送名称,您可能需要使用表单并使用提交按钮而不是链接,因为它代表的是操作而不是链接。

<%= form_tag(:controller => "profile", :action => "create_profile") do -%> 
    <%= hidden_field_tag :name, @user.profile.todotext %> 
    <%= submit_tag "Todo Text" %> 
<% end -%> 
+0

太好了,谢谢!使用'form_tag'是唯一正确执行该操作的方法吗?我特别想使用'link_to',因为它让我的代码更清晰。 – tvalent2

+0

实际上你应该使用'button_to'如果你的POST请求 – daniel

+0

难题,有没有其他的方法来保持名称的URL? – tvalent2