Selecting Associated records with Rails and simple form

172 Views Asked by At

I have a project with partials associated with it. I am trying to create a selection box so that the user can select a parcel from the associated parcels to add to another model associated with the project. What I have below is my attempt that displays the parcels but simply returns the id ie I get

undefined method `each' for "64":String 

With 64 being the parcel's ID.

I would also like to allow the user to select multiple parcels or no parcels.

 <% @pro_par = @project.parcels %>
 <%= f.input :parcels, :collection => @pro_par, :label_method =>:tax_parcel %>

How can I fixe this?

1

There are 1 best solutions below

0
On

If you already have a associated model like

class Article < ActiveRecord::Base
  has_many :parcels
  # rest of the code
end

then you can directly call the associating models in the view using simple form

<%= simple_form_for @project do |f| %>
  <!-- remaining codes -->
  <%= f.association :parcels %>
  <%= f.button :submit %>
<% end %>

it automatically lets you select multiple parcels.

Reference: https://github.com/plataformatec/simple_form#associations