0

중첩 된 양식 : 업데이트 자녀 외국 나는 중첩 협회가

class User < ActiveRecord::Base 
    has_many :hostels 
    accepts_nested_attributes_for :hostels 
end 

class Hostel < ActiveRecord::Base 
    belongs_to :user 
end 

형태 :

<%= form_for @user do |f| %> 
<%= f.label :email %><br> 
<%= f.text_field :email %> 
<% f.object.hostels << @hostel -%> 
<%= f.fields_for :hostels do |ff| %> 
<%= ff.hidden_field :id %> 
<% end -%> 
<%= f.submit %> 
<% end -%> 

컨트롤러를

def create 
    @user = User.new(user_params) 
    raise @user.hostels.inspect 
end 

private 
def user_params 
    params.require(:user).permit(:email, hostels_attributes: [:id]) 
end 
나는 기존의 기록을 다시 연결하고 싶은

호스텔 외래 키를 업데이트하여 새 사용자에게 호스텔을 제공합니다. 이 방법은 확실히 작동하지 않습니다.

시도한 update_only: true 매개 변수도 중첩됩니다.

제목에 대한 아이디어가 있습니까? 아니면 내가 그런 수술을 시도하는 데 완전히 틀렸습니까?

답변

0

귀하가 양식으로 여러 개의 호텔을 사용할 수 있으며, 컨트롤러에 hostel_ids가 필요합니다.

모델 :

class User < ActiveRecord::Base 
    has_many :hostels 
end 

class Hostel < ActiveRecord::Base 
    belongs_to :user 
end 

형태 : 여기서 이름은 당신이 당신의 여러에서 무엇을보고 선택

<%= form_for @user do |f| %> 
<%= f.label :email %><br> 
<%= f.text_field :email %> 
<%= f.label "Hostels" %><br> 
<%= select_tag :hotel_ids, options_for_select(Hostel.all.map{|h| [h.name, h.id]}), { :multiple => true } %> 
<%= f.submit %> 
<% end %> 

컨트롤러 : 내가 코드를 테스트해야하지만하지 않았다

def create 
    @user = User.new(user_params) 
end 

private 
def user_params 
    params.require(:user).permit(:email, hostel_ids) 
end 

잘 작동합니다.