2011-06-12 3 views
0

두 모델 자동차등록이 있습니다. CarsController에서2 개의 테이블 중 조인이있는 레일 3

class Car < ActiveRecord::Base 
    belongs_to :Registration 
end 

class Registration < ActiveRecord::Base 
    has_many :cars, :dependent => :destroy 
    accepts_nested_attributes_for :cars, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 
end 

:

def index 
    @cars = Car.all 
    @cars2 = Car.all(:joins => :Registration) 
end 

보기에서는 :

<% @cars.each do |car| %> 
    <tr> 
    <td><%= car.twitter %></td> 
    <td><%= car.facebook %></td> 
    <td> 
    <% @cars2.Registration.each do |h| %> #here is my problem 
     <%= h.email %> 
    <% end %> 
    </td> 
    </tr> 
<% end %> 

이 자동차의 내 문입니다. 모든 자동차 소유자의 이메일을 인쇄하려고합니다. 전자 메일은 등록 (모델 등록) 테이블에 있습니다. 나는 데이터베이스에 쿼리를 만드는 방법을 모르겠다. 테이블에서 전자 메일을 받으려고 할 때, 테이블의 열 registration_id 자동차 테이블 등록의 id 열 ...

그래서 나는하고 싶다. 당신이 열망로드를 원하는 경우

<%= car.registration.email %> 

는 다음 컨트롤러에 다음 줄을 대신 사용 : 이메일을 가져 오기 위해 ... 당신이 팁이있는 경우, 어떻게 할 방법이 대신

답변

1

대문자로 된 연관성이 있습니다. 그것은 당신이

<% @cars.each do |car| %> 
    <tr> 
    <td><%= car.twitter %></td> 
    <td><%= car.facebook %></td> 
    <td> 
     <%= car.registration.email %> #here is my problem 
    </td> 
    </tr> 
<% end %> 
+0

젠장, 어리석은 잘못 .. . – user1946705

1

사용을 요청 :

@cars = Car.includes(:registration) 

@cars2은 필요하지 않습니다.

+0

<% = car.registration.email 컨트롤러

def index @cars = Car.includes(:registration) end 

과보기에이 개 변수를 할당해야 해달라고 또한이

class Car < ActiveRecord::Base belongs_to :registration end 

처럼 작은에 있어야합니다 %> 사용하려고했지만 오류가 발생했습니다 : "정의되지 않은 메소드'registration 'for ..."잘 모르겠지만이 오류가 발생하는 이유는 연관성이 옳습니다 (내 생각) – user1946705

관련 문제