有cart, line_item,和product, 以及一个number.
购物车按照rails敏捷开发做的,关系是一个产品有多个货号。当在选择产品的时候也同时可以选择多个货号。
相互的关系:
#cart
has_many :line_items
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity +=1
else
current_item = line_items.build(product_id: product_id)
end
current_item
end
#line_item
belong_to :product
belongs_to :product
has_many :number
#product
has_many :line_itmes
has_many :number
#number
belong_to :line_item
belong_to :product
#product.show 控制器
def show
@
product = Product.find(params[:id])
@
numbers = @
product.numbers
end
#line_item 的控制器
def create
product = Product.find(parms[:product_id])
@
line_item = @
cart.add_product(product.id)
if @
line_item.save
redirect_to cart_path
end
end
在product 的show view视图。
<%= form_for([@product, @
product.line_items.build]) do |f| %>
<% @
numbers.each do |number| %>
<li><%= check_box_tag 'line_item[number_ids][]', number.id,
@
line_item.numbers.map(&:id).include?(number.id) %>
<%= number.number %>
</li>
<% end %>
<%= f.hidden_field_tag 'line_item[number_ids][]', ' ' %>
<%= f.submit %>
<% end %>
这样能添加数据
Parameters{"utf8"=>"✓","authenticity_token"=>"HCbW5r22boi1QrXPAT1as0EDKUiqxHQDjvM=", "line_item"=>{"number_ids"=>["28", "29", ""]}, "commit"=>"Create Line item", "locale"=>"en", "product_id"=>"2"}
但是没有添加进数据库, 后来我想在控制器create中定义创建line_item
def create
@
product = Product_find(params[:product_id])
@
line_item = @
cart.add_product(product.id)
@
line = @
product.line_items.new(parms[:line_item])
if @
line_item.save && @
line.save
redirect_to cart_path
end
end
Number Load (0.4ms) SELECT `numbers`.* FROM `numbers` WHERE `numbers`.`line_item_id` = 101
=> [#<Number id: 26, number: "222", product_id: 6, created_at: "2013-12-19 09:20:29", updated_at: "2013-12-20 01:16:24", line_item_id: 101>, #<Number id: 27, number: "1111", product_id: 6, created_at: "2013-12-19 09:20:29", updated_at: "2013-12-20 01:16:24", line_item_id: 101>]
这样就添加进数据库。但是这样以下子就创建了二个,而@
line所创建的却没有关联购物车cart_id是空的。
#<LineItem id: 100, cart_id: 27, product_id: 6, created_at: "2013-12-20 01:16:24", updated_at: "2013-12-20 01:16:24", quantity: 1>,
#<LineItem id: 101, cart_id: nil, product_id: 6, created_at: "2013-12-20 01:16:24", updated_at: "2013-12-20 01:16:24", quantity: 1>,
想咨询社区的高手帮忙看看这个要怎么做。谢谢