2012-08-01 89 views
0

我想在has_many上編輯3模型。我的問題是有關控制器和我如何可以訪問信息編輯無的內容

我有以下型號

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

他有關係遵循

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 

當客戶想要編輯的內容,如果有的話,我想成爲最新的一個。我目前的查詢似乎沒有處理空案,也不知道該怎麼做。

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

我應該如何在客戶控制器的def編輯中聲明它?

更新:我希望能夠看到我的數據,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 

我翻譯一個部分從書的文件夾,我應該選擇創建可在客戶控制器或在書籍控制器

更新:使用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 2012-08-01 00:39:00

+1

爲什麼它值得,Array#空?是一種乾淨的方式來檢查數組是否有任何元素。 – 2012-08-01 00:39:57

+0

是的,它會創建一個新實例。 @PeteSchlette,這是一個很好的,我忘記了這一點。 +1。 – sosborn 2012-08-01 00:42:47