【发布时间】:2015-04-28 18:41:36
【问题描述】:
我是 Rails 新手,在理解关联的正确用法方面有些困难,因此在让我的代码正常工作时遇到了问题。我已经查看了 rubyonrails.org,但仍然不确定。
我有 3 张表 (mySQL),一张将包含产品,一张用于销售这些产品的零售商,一张将产品链接到零售商并有价格。一个零售商可以储存许多产品,一个产品可以由许多零售商销售。出于这个原因,我采用了“拥有许多并属于许多”的方法。
我的 API 将返回 json,其中包含有关产品的详细信息 + 销售产品的零售商 + 零售商的销售价格。
当我运行我的代码时,我收到以下错误:
“在 ProductPrice 上找不到名为 'products' 的关联;也许你拼错了?”
我的模特:
class ProductPrice < ActiveRecord::Base
end
class Products < ActiveRecord::Base
has_and_belongs_to_many :productprices
end
class Retailer < ActiveRecord::Base
has_and_belongs_to_many :productprices
end
控制器:
module Api
module V1
class ProductDetailsController < ApplicationController
def show
@prod = ProductPrice.joins(:products, :retailers)
render json: @prod
end
end
end
end
迁移文件:
class CreateRetailers < ActiveRecord::Migration
def change
create_table :retailers do |t|
t.string :name
t.string :url
t.string :aff_id
t.string :img_url
t.timestamps
end
end
end
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.string :brand
t.string :category
t.string :sub_cat
t.string :nut_cal
t.string :nut_pro
t.string :nut_fat
t.string :nut_sat_fat
t.string :nut_carb
t.string :nut_sugar
t.string :nut_salt
t.text :ingredients
t.string :flavours
t.text :description
t.string :img_url
t.timestamps
end
end
end
class CreateProductPrices < ActiveRecord::Migration
def change
create_table :product_prices do |t|
t.belongs_to :product, index: true
t.belongs_to :retailer, index: true
t.string :price
t.string :aff_link
t.timestamps
end
end
end
几个问题:
- 鉴于我试图实现的场景,我是否使用了正确的
协会? -
我需要进行哪些更改才能解决错误?
谢谢。
【问题讨论】:
-
你需要在数据库中创建一个连接表才能拥有has_and_belongs_to_many关系。
标签: mysql ruby-on-rails