3

データベースに2つのテーブル、つまりproductsとshopping_listを作成しました。私は製品にshopping_listの外部キー参照、すなわちproduct.shopping_list_idを与えました。

Ruby on Railsで結合を実装しようとしていますが、エラーが発生します

私のroutes.rbファイルは次のとおりです

Shop::Application.routes.draw do
  resources :shopping_lists do
    member do
     post 'add'
     get 'delete'
    end

    collection do
     get 'add'
     get 'joins'
     get 'list'     
     post 'get_shopping_lists'
    end
  end

  resources :shopping_lists

  # ---- Contact Routes ------

  resources :products do
    member do
     post 'add'
     get 'delete'
    end

    collection do
     get 'add'
     get 'list'  
     post 'get_products'   
    end
  end  

  resources :products

私のproduct.rbは

class Product < ActiveRecord::Base


        attr_accessible :id, :shopping_list_id, :product_name, :product_category, :quantity, :status

        # ------- ASSOCIATIONS --------

        belongs_to :shopping_list


        # ------ VALIDATIONS ------

        validates_presence_of    :id, :product_name

        validates_uniqueness_of  :id

        # -------- SCOPES ----------

        # scope :not_deleted, where("products.deleted = 0")

        # default_scope not_deleted

    end

私のshopping_list.rbは

class ShoppingList < ActiveRecord::Base
    attr_accessible :id, :shopping_list_name, :shopping_list_status, :total_items, :created_by, :last_updated_by

    # ------- ASSOCIATIONS --------

    has_many :products


    # ------ VALIDATIONS ------

    validates_presence_of    :id, :shopping_list_name

    validates_uniqueness_of  :id

    # -------- SCOPES ----------

    # scope :not_deleted, where("shoppinglistsqa.deleted = 0")

    # default_scope not_deleted
end

私が実装しようとしているクエリは

select shopping_lists.shopping_list_name,shopping_lists.id,products.product_name,products.product_category
from products,shopping_lists
where shopping_lists.id=products.shopping_list_id;

手伝ってくれませんか。

4

1 に答える 1

3

次のようなことをしてください:

@products = Product.includes(:shopping_lists)
# if you want to get all products + their shopping list

@shopping_list = ShoppingList.includes(:product).find(params[:id])
# if you want to return just 1 shopping_list + it's product

@product = Product.includes(:shopping_lists).find(params[:id])
# if you want to return a specific product + all of it's shopping lists

データベース クエリに関する詳細については、こちらを参照してください

于 2013-02-16T04:24:39.230 に答える