views:

118

answers:

2

Okay. So I have three models, a, b and c. a has_one c, b has_many cs, and c belongs_to both a and b. When I reference "cs" in a method of b, it comes out fine. But when I reference "c" in a method of a, it can't find the reference; it says "c" is an 'undefined local variable or method'. I know that c objects are getting created, because they appear in the MySQL database, and I can access them perfectly well from the b model, but I can't access them from the a model.

A: 

class A < ActiveRecord::Base has_one :c, :dependent => :destroy

class B < ActiveRecord::Base has_many :c

class C < ActiveRecord::Base belongs_to :a belongs_to :b

Create method in as_controller:

def create @a = a.new(params[:a]) params[:b][:venue_id] = get_venue_id_for_b unless params[:venue][:name].blank? @a.user = @user @a.b = B.new(params[:b]) @b = @a.b @b.valid? @a.valid?

respond_to do |format|
  if @a.valid? and @b.valid?
    if (@a.duplicate? or @a.save) and @b.save
      flash[:notice] = 'a was successfully created.'
      format.html { redirect_to a_url(@a) }
      format.xml  { head :created, :location => a_url(@a) }
    else
      format.html { render :action => "new" }
      format.xml { render :xml => @a.errors.to_xml and @b.errors.to_xml }
    end
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @a.errors.to_xml and @b.errors.to_xml }
  end
end

end

This method within model B works:

def q puts cs.class end

This method within model A does not work:

def q puts c.class end

It is still hard to see whats going on, I am assuming you have your foreign keys specified correctly. E.g. the C table should have 2 keys "a_id" and "b_id". That being said, in your C model, a "has_many :c" doesnt make sense. You would use the plural form "has_many :cs".
Cody Caughlan
+1  A: 

Your problem comes from your specification of the relationships.

It seems you're looking for something along these lines

class a < ActiveRecord::Base
  has_one :c, :through=>:b
end


class b < ActiveRecord::Base
  has_many :c
end


class a < ActiveRecord::Base
  belongs_to :b
end

That should allow you to run the query properly. Hope this helps.

Christopher Hazlett