3

我在数据库中创建了两个表,即 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 回答