2017-04-18 8 views
1

간단한 예제를 스캐 폴딩하여 문제를 설명합니다. 이 예에서는 우주선과 파일럿이 있습니다. 나는 창조 할 때 우주선에 기존의 조종사를 배치 할 수 있기를 원한다.선택 태그를 사용할 때 모델 (# ...)이 예상 됨 (# ...) 오류가 발생했습니다.

starship.rb

class Starship < ApplicationRecord 
    has_one :pilot 

    validates :name, presence: true 
end 

pilot.rb

class Pilot < ApplicationRecord 
    belongs_to :starship, optional: true 

    validates :name, presence: true 
end 

우주선/_form.html.erb

<div class="field"> 
    <%= f.label :pilot %> 
    <%= f.select :pilot, Pilot.all %> 
</div> 

starships_controller.rb

def starship_params 
    params.require(:starship).permit(:name, :pilot) 
    end 

PARAMS 해시

{"name"=>"Nostromo", "pilot"=>"#<Pilot:0x007f85ff547f90>"} 

그리고이 오류를 얻을

Pilot(#70106745549840) expected, got String(#70106709663840) 

내가, 내 파일럿이 해시의 문자열로 전송되는 것을 볼 수 있지만 나는 그것이 어떻게해야 하는지를 찾지 못하는 것 같습니다.

+2

그런 매개 변수 해시에 객체를 전달할 수 없습니다. 당신은 그 객체의'id'를 보내고 나중에 목적지의 객체를 찾을 수 있습니다. –

답변

4

컬렉션 선택을 사용하고 파일럿 ID 만 반환하십시오. 당신이

def starship_params 
    params.require(:starship).permit(:name, :pilot_id) 
    end 

에 대한 attr_accessor 추가하여 starship_params을 변경해야합니다

<%= f.collection_select(:pilot_id, Pilot.all, :id, :name) %> 

참고 : pilot_id

class Starship < ApplicationRecord 
    attr_accessor :pilot_id 

다음과 같이이 생성, 수정 ...

def create 
    @starship = Starship.new(starship_params) 
    @starship.pilot = Pilot.find(@starship.pilot_id) 
    respond_to do |format| 
    ... 
+0

나는 이걸 시도했지만 지금이 오류가 나옵니다.''Starship id : nil, name : nil, created_at : nil, updated_at : nil>에 대해'undefined method'pilot_id '를 찾으셨습니까? 조종사'. 내가 실수했을지도 모르는 어떤 아이디어? – LRP

+0

아, 맞아, 미안, 그건 'has_one'이야. 답변 수정 됨. 환호 – SteveTurczyn

+0

완벽하게 고마워요. – LRP

0

당신은 1 대 1의 작전을 가지고 있습니다. 관계. 모든 조종사를 나열하면이를 덮어 쓸 수 있습니다. 전체 목록에서 하나를 지정하는 것보다 새로운 파일럿을 만드는 것이 좋습니다.

그래도 사용하려면이 코드를 사용하십시오. 파일럿을 전송하려는 경우 아래 Pilot.pluck(:id)을 사용할 수도 있습니다. 당신의 starship_controller에서 지금

<div class="field"> 
    <%= f.label :pilot_id %> 
    <%= f.select :pilot_id, Pilot.where('starship_id is NULL').pluck(:id) %> 
</div> 

+0

나는 ID없이 조종사를 찾을 수 없습니다. 나는 대신'f.select : pilot'과'params.require (: starship) .permit (: name, : pilot)'을 시도해 본 다음에 원래의 에러를 다시 얻었습니다. – LRP

0

그냥 코드 아래에 대체 ... 당신의 강력한 PARAMS가

def starship_params 
    params.require(:starship).permit(:name, :pilot_id) 
end 

희망이 도움이되어야한다

def create 
    @starship = Starship.new(starship_params) 
    pilot = @starship.build_pilot 
    pilot.id= params[:starship][:pilot_id] 
    pilot.reload 
    respond_to do |format| 
     if @starship.save 
     format.html { redirect_to root_path, notice: 'Starship successfully created.' } 
     else 
     format.html { redirect_to root_path, notice: 'Error occured.' } 
     end 
end 

쓰기 방법을 만들 수 코드로 너는 잘 가라.

<%= f.label :pilot %> 
<%= f.select :pilot, Pilot.all.map{ |p| [p.name, p.id] } %> 

은 선택 드롭 다운에 조종사의 이름을 표시하고 저장하는 동안 특정 파일럿의 ID를 저장합니다.

+0

여전히이 에러와 동일한 오류가 발생했습니다. "name"=> "Nostromo", "pilot"=> "2"}' – LRP

관련 문제