2012-07-19 2 views
0

У меня есть три модели. Родитель, ребенок, тип и отношения. Связь - это модель богатого объединения, ссылающаяся на родителя, ребенка и тип.рельсы вложенные атрибуты has_many через

Проблема заключается в том, что при создании дочернего элемента и создании таблицы отношений родительский элемент в таблице отношений не заполняется. Только ребенок и тип автоматически заполняются.

parent.rb

attr_acccessible :relationships_attributes 

has_many :relationships 
has_many :children, :through => :relationships 
has_many :types, :through => :relationships 

child.rb

attr_acccessible :relationships_attributes 

has_many :relationships 
has_many :parents, :through => :relationships 
has_many :types, :through => :relationships 

accepts_nested_attributes_for :relationships 

relationship.rb

attr_accessible :parent_id, :child_id, :type_id 
belongs_to :parent 
belongs_to :child 
belongs_to :type 

children.controller

def new 
@child = Child.new 
@child.relationships.build 
end 

def create 
@child = Child.new(params[:child]) 
if @child.save 
    redirect_to current_user 
else 
    render "new" 
end 
end 

new.html.erb

<%= simple_form_for @child do |f| %> 
    <%= f.input :first_name, :label => 'First Name' %> 
    <%= f.input :gender, :as => :select, :collection => ['Male', 'Female'] %> 
    <%= f.association :relation_types, :as => :collection_select %> 


    <%= f.button :submit, :class => "primary" %> 

<% end %> 

Пожалуйста, помогите.

Спасибо!

ответ

2

, кажется, вы забыли много вещей:

@child.relationships.build 

должно быть

@child.relationships.build :parent_id => ... 

и ввиду вместо

f.association :relation_types, :as => :collection_select 

использование

f.field_for :relationships do |g| 
    g.association :types, :as => :collection_select 
    g.hidden :parent_id #need to save this 
+0

Спасибо за это. Есть ли другой способ включить родительский идентификатор? Я предпочитаю не использовать скрытые поля. – noob

+0

Если вы не хотите его в родительском id, возможно, вы можете скрыть его в параметрах (изменение формы url или изменение маршрутов.rb сделать этот ресурс вложенным (это непросто)) – qoyyim

+0

Вы также можете использовать '@child = @ parent.children. build' – qoyyim

Смежные вопросы