2011-11-10 17 views
0

我有一个父模型,一个子模型和一个连接模型。如果我需要引用parent_id和child_id,那么连接模型的控制器是怎样的?rails - 首选表单

例如,我有:

def new 
    @join = JoinModel.new 
new 

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

我的问题是,我该如何引用子模型对象?

如果我使用@child = Child.find(params[:id]), it gives me the error找不到没有ID的孩子。

帮助。

谢谢。

回答

0

两个小技巧:

1)尽量使用这个自引用的模型 - 只有一个表,而不是三个表 - 这是一个较瘦的设计。 2)使用“血统”宝石来模拟父母/孩子 - 它有非常方便的方法去父母,祖先或后代。

参见:

http://railscasts.com/episodes/262-trees-with-ancestry(动手RailsCast)

Self-referencing models in Rails 3


如果你需要这些模型是独立的,你可以做这样的事情:

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 

然后创建像这样的新出版物:

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

这是不是一个真正的父/子关系,而是 “通过的has_many”

+0

感谢@Tilo。我不确定自引用模型是否适用于此,因为父模型是“用户”,子模型是“发布”。这不是用户与用户的连接。 – noob

+0

检查上面的扩展答案 – Tilo