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

customercontrollerの定義編集でどのように宣言すればよいですか??

更新: 自分のデータを表示できるようにしたいのですが、残念ながらここでは機能していないようです

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

作成オプションがカスタマー コントローラーまたは bookControllers にある場合、ブック フォルダーからパーシャルをレンダリングしています。

更新: customerController を使用すると、メインの作成が行われます。ブック コントローラーで不足しているアクションを作成するときに、ブック コントローラーでさらにアクションを実行する必要がありますか?

4

1 に答える 1

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
于 2012-08-01T00:33:31.507 に答える