多个模型嵌套,数据关联的问题

2013-12-20 10:34:32 +08:00
 yehkevin
有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>,


想咨询社区的高手帮忙看看这个要怎么做。谢谢
3625 次点击
所在节点    Ruby on Rails
3 条回复
ygmpkk
2013-12-20 12:43:15 +08:00
大哥,你把代码贴到 https://gist.github.com
yehkevin
2013-12-20 13:31:45 +08:00
@ygmpkk 就把这些贴上去的吗
ygmpkk
2013-12-23 11:30:41 +08:00
@yehkevin 对的,然后把url贴在这里,就可以自动显示出来。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/93899

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX