0

I have a parent model, a child model and a join model. How does the controller of the join model look like if I need to reference the parent_id and the child_id?

For example, I have:

def new
  @join = JoinModel.new
new

def create
  @join = JoinModel.new(params[:join_model])
  @parent_id = current_user.id
end

My question is, how do I reference the child model object?

If I use @child = Child.find(params[:id]), it gives me the errorcan't find child without an ID`.

Help.

Thanks.

noob
  • 1,807
  • 2
  • 18
  • 34

1 Answers1

0

Two Tips:

1) try to use a Self-Referential model for this -- just one table instead of three tables - that's a more lean design.

2) use the "ancestry" Gem to model parents / children - it has very convenient methods to get to the parent, ancestors, or descendants.

See:

http://railscasts.com/episodes/262-trees-with-ancestry (hands-on RailsCast)

Self-referencing models in Rails 3


If you need those models to be separate, you can do something like this:

class User < ActiveRecord::Base
  has_many :publications, :through => :ownership
end

class Publication < ActiveRecord::Base
  has_many :users , :through => :ownership
end

class Ownership < ActiveRecord::Base   # the join table
  belongs_to :user
  belongs_to :publication
end

and then create new publications like this:

   u = User.find_by_name("John")
   u.publications.new( attributes-for-new-publication )
   u.save

This is not really a Parent/Child relationship, but rather "has_many through"

Community
  • 1
  • 1
Tilo
  • 33,354
  • 5
  • 79
  • 106
  • Thanks @Tilo. I am not sure the self-referential model will work for this because the parent model is "User" and the child model is "publication". This is not a user to user connection. – noob Nov 10 '11 at 01:46
  • check the extended answer above – Tilo Nov 10 '11 at 04:29