Take the 2-minute tour ×

I have a has_many and belongs_to association.

class Link < ActiveRecord::Base     
  has_and_belongs_to_many :categories
  belongs_to :property

class Property < ActiveRecord::Base
  has_many :links

In the index and show I have <%= link.property.name %> and it will show the Property that I assigned to the link with the console just fine.

I have a problem with figuring out how to show radio buttons in the _form that assign a property to the link (a drop down would work as well).

It seems everyone who has had this question before has ether a has_many :through or a HABTM relationship and I can't seem to adapt their answers.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Since each link has only one property, you probably want radio buttons (not check boxes). This should work (in your view)

<%= form_for @link do |f| %>
  <% @properties.each do |p| %>
    <%= f.radio_button :property_id, p.id %>
    <%= f.label :property_id, p.name %>
  <% end %>

  <%= f.submit %>
<% end %>

Don't forget to set @properties = Property.all in your controller.

share|improve this answer
Rad. The radio buttons (I can't believe I was searching for check boxes) display but there are no labels. Any idea about the label tag? –  Thomas Jan 14 '11 at 0:15
Also, if I check and submit one of the radio buttons, doesn't matter which one, it changes the property_id for the link to 0 and breaks the view because there's no name associated with the id = 0. –  Thomas Jan 14 '11 at 0:33
I messed up before (was passing the property name to the radio button instead of the id)... See updated answer (which should work correctly). Sorry! –  David Sulc Jan 14 '11 at 1:18
It's cool. It works now. Thank you very much for your time. –  Thomas Jan 14 '11 at 3:47
add comment

Your Answer


