0

테이블이 customer, customer_site, siteconnection 인 테이블이 4 개 있습니다. customersite은 다수가 customer_sites이고 site이 많으므로 connections입니다. 이것은 내 모델에서 모두 설정되었습니다. 이제 각 고객에 대한 뷰를 확보하려고 노력 중이며 해당 고객과 연결된 모든 연결을 보여줍니다. 분명히 @connection 부분은, 내가 넣어 필요가있는 무엇 다만 확실하지 올바르지 해요되어관계형 데이터베이스보기에서 여러 테이블의 필드를 표시합니다.

def show 
    @customer = Customer.find(params[:id]) 
    @connection = Connection.all(where connection.site.customer_site.customer.id == params[:id]) 
    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @customer } 
    end 
end 

:

<% @connection.each do |l| %> 
    <tr> 
     <td><%= l.interface %></td> 
     <td><%= l.device %></td> 
     <td><%= l.speed %></td> 
     <td><%= l.site.name %></td> 
    </tr> 
<% end %> 

을이 내 컨트롤러 :이 내가 내보기에 무엇을 가지고 거기에 정확하게 레코드를 연결하려면 ...

+0

관계에 'has_many : through' 구문을 사용합니까? 그렇다면 검색을 다소 간소화 할 수 있습니다. 가장 적절한 답을 찾도록 관계를 게시하십시오. – Matt

+0

아니요, 그들은 각 컨트롤러에'belongs_to'와'has_many' 만 사용합니다. – user1738017

답변

1

@Matt가 그의 의견에서 언급 한 것처럼 가장 쉬운 방법은 has_many 연관을 :through 옵션과 함께 사용하는 것입니다. 레일에 대한 자세한 내용은 guides을 참조하십시오. 컨트롤러에서

class Site < ActiveRecord::Base 
  has_many :customer_sites, foreign_key: :site_id 
    has_many :connections 
end 

class CustomerSite < ActiveRecord::Base 
  belongs_to :site 
  belongs_to :customer 
end 
  
class Customer < ActiveRecord::Base 
  has_many :customer_sites, foreign_key: :customer_id 
    has_many :sites, through: :customer_sites 
  has_many :connections, through: :sites 
end 

: 그것은 충분히 명확하지 않은 경우

def show 
    @customer = Customer.find(params[:id]) 
    @connections = @customer.connections 
    ... 
end 

은 알려주세요.

+0

이걸 넣었습니다. 그러나 여전히 내보기에 표시되도록 올바른 구문을 모르겠습니다 ... – user1738017

+0

편집했습니다 내 대답. 또한 가이드를 읽으십시오. 연관 사용에 대한 더 많은 정보가 있습니다. – bronislav

+0

나는 우리가 말하는대로 가이드를 읽고 있는데, 나는 그것을 컨트롤러에두고 여전히 <% @ connection.each do | l | %>'내 견해로는 아직 정의되지 않은 메소드 'each'for nil : NilClass' – user1738017

관련 문제