views:

191

answers:

1

Hi. I wondered if someone could take a quick look at this. I'm making a simple conversion application which converts between units of measurement. I need to be able to self reference the table using a join table which stores the relationship between each, along with the conversion between each. This then would be referenced between either side of the relationship. For example 1cm = 10mm and 10mm = 1cm.

So thus far I have this:

#migrations
create_table :measures do |t|
    t.string :name
end

create_table :measure_measures do |t|
    t.integer :measure_id
    t.integer :related_measure_id
    t.integer :conversion
end

class Measure < ActiveRecord::Base    

    has_many :related_measures,  
        :foreign_key => 'measure_id',
        :class_name => 'MeasureMeasure',
        :dependent => :destroy

    has_many :measures,  :through => :related_measures

    accepts_nested_attributes_for :related_measures, 
        :reject_if => proc { |attrs| attrs['related_measure_id'].blank? ||  
                                     attrs['quantity'].blank? }, 
        :allow_destroy => true      
end

#controller
    @measure = Measure.find params[:id

#form
    <% form_for @measure do |f| %>
        <% fields_for :related_measures do |f_r_m| %>
            <%= f_r_m.text_field :related_measure_id -%>
            <%= f_r_m.text_field :quantity -%>
        <% end %>
    <% end %>

For the most part this works ok. Except I cannot access the name of the related measure, only the owner.

I need to get it somehow like this:

f_r_m.object.related_measure.name

but clearly despite my best efforts i cannot set it up and receive the error.

undefined method `owner_measure' for #<MeasureMeasure:0x1053139a8>

Help would be very much appreciated. :)

A: 

At first glance the problem comes from the has many through definition. By failing to define the foreign key, Rails, assumes measure_id in the join table. Which would just link back to the measure you're trying to find it from.

has_many :measures,  :through => :related_measures, :foreign_key => :related_measure_id

We can't diagnose this error without seeing the innards of the join model.

f_r_m.object.related_measure refers to join table.

But I suspect it's because you haven't defined the relationship properly in the join model. Which should look something like this:

class MeasureMeasures < ActiveRecord::Base
    belongs_to :measure
    belongs_to :related_measure, :classname => "Measure"
end
EmFi
Thanks very much! You're absolutely right about the join table being the problem. As you can see by my not posting it here I wasn't paying it enough attention and the join was indeed defined incorrectly. In fact it was my simply changing my mind as to how to name it - 'owner_measure' instead of 'related_measure'.Thanks again!
mark