Displaying related tables in forms.. probably an easy questi


#1

Hey All,

I have two tables… One belongs to another. Why can’t I reference
table1.table2.attribute?

Specifically, using scaffolding:
property.rb -
has_one :PropertyType

property_type.rb -
has_many :Properties

property_controller -
def list
@property_pages, @properties = paginate :properties, :per_page => 10
end

list.html:

  1. <% for property in @properties %>
  2. <% for column in Property.content_columns %>
    
  3.   <td>
    
  4.     <%=h property.send(column.name) %>
    
  5.   </td>
    
  6. <% end %>
    
  7. <td><%=h property.propertytype.name %></td>
    
  8. <% end %>
  9. Two questions:

    1. I get an error stating that I am trying to reference the propertytype
      method on line #8. I thought I was doing this right, I’m using the
      local variable (not the instance variable which is an array of objects
      in this case).
    2. Am I doing my has_one and belongs_to statements right? Some
      documentation seems to say that you only need to use has_one and you
      don’t need belongs to? I thought you always needed them as a pair?
    • Brian

#2

You just have your associations setup wrong.
Property:
belongs_to :property_type

PropertyType:
has_many :properties

Try that and see how she flys!


#3

The fact that you named property_type the way you did with an underscore
makes it especially important that you understand how Rails deals with
names. I’m not 100% sure, but try referencing property.property_type,
with the underscore. Rails will know it as PropertyType and
property_type depending on the context, but not as propertytype.

Brian C. wrote:

Hey All,

I have two tables… One belongs to another. Why can’t I reference
table1.table2.attribute?

Specifically, using scaffolding:
property.rb -
has_one :PropertyType

property_type.rb -
has_many :Properties

property_controller -
def list
@property_pages, @properties = paginate :properties, :per_page => 10
end

list.html:

  1. <% for property in @properties %>
  2. <% for column in Property.content_columns %>
    
  3.   <td>
    
  4.     <%=h property.send(column.name) %>
    
  5.   </td>
    
  6. <% end %>
    
  7. <td><%=h property.propertytype.name %></td>
    
  8. <% end %>
  9. Two questions:

    1. I get an error stating that I am trying to reference the propertytype
      method on line #8. I thought I was doing this right, I’m using the
      local variable (not the instance variable which is an array of objects
      in this case).
    2. Am I doing my has_one and belongs_to statements right? Some
      documentation seems to say that you only need to use has_one and you
      don’t need belongs to? I thought you always needed them as a pair?
    • Brian