2012-08-01 69 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