如何通过link_to将参数传递给_form?

时间:2016-06-03 02:01:15

标签: ruby-on-rails ruby view parameters

如何将challenge.name从挑战/索引传递到挑战/形式:

表单视图

<%= simple_form_for(@challenge)  do |f| %>
  <%= f.text_field :name, placeholder: 'Enter Challenge' %>
  <%= button_tag(type: 'submit')  do %>
    Save
  <% end %>
<% end %>

索引视图

<% @challenges.each do |challenge| %>    
  <%= link_to new_challenge_path(challenge: {name: challenge.name}) do %>
    + Challenge
  <% end %>
  <%= challenge.name %>
<% end %>

challenges_controller

def new
  @challenge = Challenge.new
  respond_modal_with @challenge, location: root_path
end

使用上面的代码,如果用户点击link_to我看到它正在服务器中传递,如下所示,但challenge.name没有出现在text_field代替placeholder文字。

rails s

Started GET "/challenges/new?challenge%5Bname%5D=HOPE+THIS+WORKS" for 127.0.0.1 at 2016-06-02 21:52:37 -0400
Processing by ChallengesController#new as */*
  Parameters: {"challenge"=>{"name"=>"HOPE THIS WORKS"}}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 15]]
  Rendered challenges/new.html.erb within layouts/modal (8.2ms)
Completed 200 OK in 15ms (Views: 11.2ms | ActiveRecord: 0.4ms)

1 个答案:

答案 0 :(得分:2)

您的link_to仅在GET params中添加了挑战名称。然后,您需要将这些参数传递给新构造的@challenge对象,以便简单表单可以使用它(表单适用于对象的属性,而不是GET / POST参数)。因此,尝试将控制器更改为:

def new
  @challenge = if params[:challenge]
    Challenge.new(params.require(:challenge).permit(:name))
  else
    Challenge.new
  end
  respond_modal_with @challenge, location: root_path
end