AnthonyGalli.com AnthonyGalli.com - 6 months ago 10
Ruby Question

How to pass a parameter via link_to into _form?

How do I pass

challenge.name
from challenges/index into challenges/form:

form view

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


index view

<% @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


With the above code if a user clicks the
link_to
I see it is passing in the server as shown below, but the
challenge.name
is not appearing in the
text_field
in place of the
placeholder
text.

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)

Answer

Your link_to only adds the challenge name among GET params. You then need to pass those params to the newly constructed @challenge object so that simple form can use it (form works with attributes of the object, not GET / POST params). So, try changing the controller to something like:

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