2011-10-16 29 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