2012-05-11 4 views
0

우리는 3 모델의 model1, model2, model3 있습니다. 이 3은3 개의 모델이 레일에 연결되어 있습니다. 3

class Model1 < ActiveRecord::Base 
    has_many :model2s 
end 
class Model2 < ActiveRecord::Base 
    belongs_to :model1s 
    has_many :model3s 
end 
class Model3 < ActiveRecord::Base 
    belongs_to :model2s 
end 

과 연결됩니다. Model1의 테이블에 ID가 있습니다.

Model2의 테이블에는 id 및 model1_id가 있습니다.

Model3의 테이블에는 id 및 model2_id가 있습니다.

지금 내가 Model3Controller 밖으로 표 1과 표 2에서 데이터를 얻을 싶어요. 이 작동합니다.

class Model3Controller < ApplicationController 
    def create 
    @model2controller = Model2.find(params[:model3controller][:model2_id]) 
    @model1controller = ? 
    end 
end 

model1 컨트롤러의 table1에서 관련 데이터 세트의 데이터를 가져 오는 방법은 무엇입니까? model3_id를 table3에 추가해야 했습니까? 아니면 다른 방법으로 호출 할 수 있습니까? 이 의사

@model1controller = Model1.find(
params[:model3controller][:model2_id]params[:model2controller][:model1_id]) 
+0

[이 가이드]에서 봐 주시기 바랍니다 (http://guides.rubyonrails.org/association_basics.html). belongs_to 항상 – shuriu

+0

달성하기 위해 노력하고 무엇을 정말 잘 설명 생각합니다. Model2.Model1' 정의되지 않은 메서드 Model2 for nil : NilClass – amarradi

답변

1

처럼 내가 뭔가를 누락 될 수 있습니다,하지만 당신은 다음을 수행해야 같습니다

model1 = Model3.find_by_id(params[:model3_id]).model2.model1 

편집합니다. 위의 코드는 다음 줄과 같이 작동

model3 = Model3.find_by_id(params[:model3_id]) # instantiate a model3 

model2 = model3.model2 # from mode3 grab a model2 
         # this is possible due to the fact that model3 is associated with model2 via the belongs_to relation 

model1 = model2.model1 # model2 "belongs_to" model1, i.e. we can grab model1 by asking model2: "whom do belong to?" just like in the previous example 

인스턴스 메서드를 액세스하는 당신이 실수를 즉, 귀하의 예제에서

object.method # => something is returned 

, 소문자로 호출 이루어집니다 유의하시기 바랍니다 (Model3.find_by_id(params[:id]).Model2를 호출 Model2에 대문자가 있음을주의하십시오.)

또한 params [: id]가 실제로 컨트롤러 작업에 전달되는지 확인하십시오. 그렇지 않으면, 그것이 없으면 Model3.find_by_id(params[:id])nil을 반환 할 것이고, 따라서 언급 된 오류가 발생할 것입니다.

+0

단수이 나에게 오류'@ model1controller = Model3.find_by_id (PARAMS [: ID]를) 제공합니다 나는 당신이 내가 버그 발견 .. – amarradi

+0

Answer 배경을 설명해 주시겠습니까? – amarradi

+0

@amarradi 나는 대답을 – gmile

관련 문제