3
votes

I'm using simple_form and I'd like to pre-populate several fields in my form. In the link to the form I'm passing several values to params in the URL. The trouble comes in when I either try to pass a value to a field that is an integer or an association. In either case, the field does not pre-populate.

Example below...the first two fields populate fine, but I had to force them to be text fields. Maybe that's ok to push the strings from the url into the field, but ideally I'd be able to use either the integer (f.input) or association (f.association). The second two fields don't pull in the param values from the URL.

Any ideas? Thanks in advance!

NOTE - this is for generating a NEW record in the database and not for editing an existing record.

URL: http://localhost:5000/list/new?event_id=4&user_id=11

<!-- These two fields pre-populate -->
<%= f.text_field :event_id, :value => params[:event_id] %>
<%= f.text_field :user_id, :value => params[:user_id] %>

<br>

<!-- These two fields do NOT pre-populate -->
<%= f.association :event_id, :value => params[:event_id] %>
<%= f.input :event_id, :value => params[:event_id], label: 'Event' %>

PS - I'm listening to GusGus' new album on Spotify while working on this and it's helping a lot. :)

1
I don't think you association syntax is right... I think it should be :events, not :event_id, and you should have a lambda for selected instead of :value... Check this: stackoverflow.com/questions/19262954/…Ruby Racer
you're right..that was a typing error. it's :event for the association.jakeatwork

1 Answers

4
votes

Best practice is pre-populate form not with params directly but with ActiveRecord object. For example you have an AR class:

class Party < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

Then in your controller:

def new
  @party = Party.new(party_params)
end

# use strong params to make your parameter more secure;)
def party_params
  params.permit(:event_id, :user_id)
end

and then in your edit view:

<%= simple_form_for @party do |f| %>
  <%= f.association :event %>
  <%= f.association :user %>
<% end %>