将表连接到购物车

时间:2011-12-29 13:16:00

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

将桌子连接到购物车

我有三个模型和三个数据库表,我想连接到一个购物车,我是新的rails并且有一些问题要做到这一点。 我最初的想法是 创建名为Service的模型作为模型Adverts,Package_of_products和Subscriptions的父模型。然后通过Line_item将其连接到购物车 已经知道我做错了什么 每次尝试将我的一项服务添加到Line_items时,我都会收到消息

ActiveRecord::RecordNotFound in LineItemsController#create

Couldn't find Service without an ID

app/controllers/line_items_controller.rb:44:in `create'

我已经

def create
  @cart = current_cart
  service = Service.find(params[:service_id])
  @line_item = @cart.line_items.build(:service => service)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.')   
end

我有4个数据库并为我的Line_items建模

class LineItem < ActiveRecord::Base
belongs_to :service
belongs_to :cart
end

class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
has_many :services,
has_many :adverts, :through => :services
has_many :package_of_products, :through => :services
has_many :subscriptions,:through => :services

广告

class Advert < ActiveRecord::Base
  belongs_to :service
end

订阅

class Subscription < ActiveRecord::Base
  belongs_to :service
end

Package_of_products

class PackageOfProduct < ActiveRecord::Base
  belongs_to :service
end

1 个答案:

答案 0 :(得分:2)

好的,首先关联名称是belongs_to而不是belong_to,所以请更正错误打印。

然后我认为你需要这样的smth:

class Cart  < ActiveRecord ::Base
  has_many :line_items, :dependant => destroy
  has_many :ads, :through => :line_items
  has_many :products, :through => :line_items
  has_many :services, :through => :line_items
end

检查has_many :through关联here