rails: many to many agony

G

Graham Arrowsmith

I have two classes: Projects and Company. There are many to many
relationships between companies and project and are joined by table
company_projects

Thing is when I render out a select list I want to make the related
dropdown items selected :

<select name="project[company_id]">
<% @companies.each do |company| %>
<option value="<%= company.id %>" >
<%= ' selected' if company.id == @project.companies.id %>
<%=company.companyName %>
</option>
<% end %>
</select>

However I can't seem to be able to get the project.companies.id (ie
company_project.company_id) for the related project.

I know this is pretty darn simple but I can't seem to crack it.

Any help would be appreciated!

Graham
 
D

Dave Burt

Graham Arrowsmith said:
I have two classes: Projects and Company
[with a many-to-many relationship]

<select name="project[company_id]">
<% @companies.each do |company| %>
<option value="<%= company.id %>" >
<%= ' selected' if company.id == @project.companies.id %>

<%=company.companyName %>
</option>
<% end %>
</select>

(Does that make a multiple-select? I thought I had to add the html_options
parameter {:multiple => 'multiple'}.)

Cheers,
Dave
 
L

Luca Pireddu

Graham said:
I have two classes: Projects and Company. There are many to many
relationships between companies and project and are joined by table
company_projects

Thing is when I render out a select list I want to make the related
dropdown items selected :

<select name="project[company_id]">
<% @companies.each do |company| %>
<option value="<%= company.id %>" >
<%= ' selected' if company.id == @project.companies.id %>
<%=company.companyName %>
</option>
<% end %>
</select>

However I can't seem to be able to get the project.companies.id (ie
company_project.company_id) for the related project.

I know this is pretty darn simple but I can't seem to crack it.

Any help would be appreciated!

Graham

I've just begun using activerecord, so take my suggestion with a grain of
salt :)

project.companies should return an array of companies, no? That makes it
wrong to say project.companies.id. I think you want something like

<%= ' selected' if @project.companies.member?(company) %>

Array#member? uses == to test for equality, and I think I remember reading
that AR overrides == to test for the equality of the "id" field so the
comparison should work.

Hope that helps.

Luca
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top