2012-08-01 5 views
0

has_many에서 3 모델을 편집하고 싶습니다. 자신이 가지고 관계는콘텐츠를 편집하지 않고

고객이 내용을 편집하고자
Customer 
    has_many book_managers 
    has_many books :through -> book_managers 
Book 
    has_many book_managers 
    has_many customer :through -> book_managers 
Book_managers 
    belongs_to :customer 
    belongs_to :book 

에 따라 내 질문은 컨트롤러에 관한이며 어떻게 정보를 I 모델

Customer   Book   Book_Manager 
id    id    id 
first    description customer_id 
last        book_id 
email       visible 
password  

다음 한

에 액세스 할 수 있습니다 나는 존재하는 경우에 보여주는 최신 것이고 싶다. 내가 지금 가지고있는 쿼리는 빈 경우를 처리하지 못하고 그것을 수행하는 방법을 모르는 것처럼 보입니다.

@book = current_customer.books.order("created_at DESC").first 

고객 컨트롤러 정의 편집에서 어떻게 선언해야합니까 ??

업데이트 : 내 데이터를 볼 수 있도록하려면, unfoturnotly 여기가 내 나는 책 폴더 부분을 렌더링하고

customer controller 

     def create 
     @customer = Customer.new(params[:customer]) 
      @book = @customer.books.build(params[:book]) 
     if @customer.save 
     cookies[:auth_token] = @customer.auth_token 
     redirect_to @customer, notice: "Thank you for signing up!" 
     else 
      render "new" 
     end 
    end 
    def edit 
     @customer = Customer.find(params[:id]) 
     if current_customer.books.length > 0 
      @book = current_customer.books.order("created_at DESC").first 
     else 
      #Nor books were found, so create one that has the proper relationship to current_customer 
      @book = current_customer.books.build 
     end 
     end 

, 내 생성 옵션은에 있어야 작동하지 않는 것 고객 컨트롤러 또는 bookController에서

업데이트 : 사용하여 customerController는 내 주력을 만들 때 책 컨트롤러에서 누락 된 동작을 만들 때 내가 책 컨트롤러에서 더 많은 작업을해야합니까?

답변

0

컨트롤러에 책이 있는지 확인하기 만하면됩니다. 하나가 존재하지 않으면 새로운 것을 생성하십시오.

#Check if the books array contains anything. There are several ways to do this 
if current_customer.books.length > 0 
    @book = current_customer.books.order("created_at DESC").first 
else 
    #Nor books were found, so create one that has the proper relationship to current_customer 
    @book = current_customer.books.build 
end 
+0

새 인스턴스를 만들겠습니까? – Jseb

+1

가치가있는 부분에 대해 Array # empty? 배열에 요소가 있는지 확인하는 명확한 방법입니다. –

+0

예, 새 인스턴스가 만들어집니다. @PeteSchlette, 그건 좋은거야, 나는 그걸 잊어 버렸어. +1. – sosborn

관련 문제