2014-02-27 4 views
0

select 태그를 사용하여 부모 중 여러 중첩 된 자식을 저장하려고합니다. 레일 - 여러 개의 중첩 된 특성

내가

Couldn't find all UserLocations with IDs (1, 2) (found 0 results, but was looking for 2) 

찾고 있어요 오류입니다 I가 Rails 4Devise에서 다음 설정 :

사용자

class User < ActiveRecord::Base 
    has_many :user_locations 

    accepts_nested_attributes_for :user_locations, :allow_destroy => true 
end 

UserLocation (봐라 선택한 UserLocations을 저장하려고 할 때 사용자가 가지고있는 양이온)

class UserLocation < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :location 
end 

위치 (사용자에 따라 선택할 수있는 위치의 미리 정의 된 목록) 그러나

class Location < ActiveRecord::Base 
    has_many :user_locations 
    has_many :users, through: :user_locations 
end 

, 그들은 저장되지 않습니다 .

레일 선택 태그 (여러 항목을 선택할 수 있습니다)

<%= f.select :user_location_ids, options_for_select(Location.all.collect { |l| [ l.name, l.id ] }, @user.user_locations.collect{ |l| l.id }), {}, { multiple: true } %> 

내가

답변

0

를 해결 내 application_controlleruser_location_ids: []

환호에 user_location_ids을 넣어 가지고

soluti on은 다중 중첩 모델 model_ids=(value)에 대한 기본 설정 메서드를 덮어 쓰는 것입니다. 이 아닌은 모델의 복수를 사용합니다. models_ids=(value), 이 잘못되었습니다.!

def user_location_ids=(value) 
    for slot in value do 
    unless slot == "" 
     location = Location.find_by(id: slot.to_i) 
     unless location.nil? 
     self.user_locations << UserLocation.create(user_id: self.id, location_id: location.id) 
     end 
    end 
    end 
end