在rails 3.2上实现ruby中的连接时出错

时间:2013-02-16 03:52:38

标签: ruby-on-rails ruby-on-rails-3 postgresql jointable

我在数据库中创建了两个表,即products和shopping_list。 我已经为产品提供了shopping_list的外键引用,即product.shopping_list_id。

我正在尝试在rails上实现ruby中的连接但我收到错误

我的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;
你能帮助我吗?

1 个答案:

答案 0 :(得分: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

有关数据库查询的更多信息have a look here