2011-10-16 2 views
1

link_to을 사용하여 Rails 3 앱에서 객체를 만듭니다. 검색은 나에게 :post 메서드로 link_to을 사용하는 적절한 방법을 제공했지만 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 

그래서 그 link_to:name => "#{@user.profile.todotext}"에 추가 할 수있는 방법이 있나요 그것은 통과하고 저장한다? 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

실제로 POST 요청을 할 때'button_to'를 사용해야합니다. – daniel

+0

Gotcha, URL에서 이름을 지울 수있는 다른 방법이 있습니까? – tvalent2

관련 문제