S_A
S_A

Reputation: 423

Rails collection_select with join table

My tables:

enter image description here

Person belongs_to and Room has_many Person

My collection_select

 <%= collection_select(:inspection, :person_id, Person.involving(current_user), :id, :room_id) %>

If I'm not wrong, in HTML it will be represented as the following code:

<select name="post[person_id]">
        <option value="<%= person.id %>"><%= person.room_id %></option>
    <% end %>
</select>

My point is that when a user submit the form I need send the Person Id value, but I need show on the drop down list the name of the rooms (in my example I showing the room.id) like that:

<select name="post[person_id]">
        <option value="<%= person.id %>"><%= room.name %></option>
    <% end %>
</select>

How can I do that? As I see I think that I need join person table with room table? If it is the solution, how can I do that?

My person model:

scope :involving, -> (user) do
        where("persons.id = ?", user.id)
    end

My view

<%= form_for @inspection do |f| %>
      <label>Select</label>
      <%= collection_select(:inspection, :person_id, Person.involving(current_user), :id, :room.id) %>

      <%= f.submit  "Send" %>

I tried to make it as clear as I could.

Upvotes: 1

Views: 1100

Answers (1)

user483040
user483040

Reputation:

Consider using select rather than collection_select. This method allows you finer grain control over what is used for id and name of each option.

In your case you'd want something like:

select(:inspection, :person_id, Person.involving(current_user).collect {|p| [ p.id, p.room.name ] }, { ...other method options... })

This allows you to specify the array of option id/name pairs. You get all the people involved using your scope, then iterate over those returning an array for each one found, where the first value in the array is the option value and the second is the displayed option text.

Check this documentation out for more details.

Upvotes: 2

Related Questions