的has_many:经过使用,操作简单,初学者的问题 [英] has_many :through usage, simple, beginner question

查看:141
本文介绍了的has_many:经过使用,操作简单,初学者的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个简单的会计制度的管理成本。其结构是这样的:

I am writing a simple accounting system for managing costs. The structure is like this:

Invoice  - can have many products
  Product - can have many costs, also can act_as_tree 
      LineItem  - 
    Product
        LineItem
        LineItem
      Product
      LineItem
  Product
      LineItem
  LineItem

我有这个设置为一个的has_many和belongs_to的三个类,但认为以下是比较合适的(基于阅读的Rails 3路 - 有什么缺点是我缺乏了解,只是想给上下文)

I had this set up as a has_many and belongs_to for the three classes but think that the following is more appropriate (based upon reading Rails 3 Way - any shortcomings are my lack of understanding; just trying to give context)

Class Invoice < ActiveRecord::Base
    has_many :products
    has_many :line_items, :through => :products
end

 Class Product < ActiveRecord::Base
    belongs_to :invoice
    belongs_to :line_item
 end

class LineItem < ActiveRecord::Base
    has_many :products
    has_many :invoices, :through => :invoices
end

但我不这样是否正常工作。

But I don't this is working correctly.

如果我做到以下几点:

>@i=Invoice.find(1)
>@i.products # this works
>@i.line_items # doesn't work, unidentified method line_items

这是我第一次使用的has_many:通过。这是正确设置为我的数据模型?此外,是否有可能用它与acts_as_tree一起 - 我希望能够说:

This is the first time I'm using has_many :through. Is this set up correctly for my data model? Also, is it possible to use it in conjunction with acts_as_tree - I'd like to be able to say:

>@i.line_items 

和取回所有的特定发票的行项目。可能吗?

and get back all the line items for that specific invoice. Possible?

THX求助

推荐答案

首先一个问题:什么是与你的关系产品的LineItem :有1个产品线的许多项目或为1和相同的行项目在众多产品中引用?这个答案的其余部分是基于每一个产品应该有多个行项目的假设。

First a question: What is your relation between Product and LineItem: Has 1 product many line items or is 1 and the same line item referenced in many products? The rest of this answer is based on the assumption that every product should have multiple line items.

我觉得你的模型应该像这样被定义的:

I think your models should be defined like that:

# No change
Class Invoice < ActiveRecord::Base
  has_many :products
  has_many :line_items, :through => :products
end

# Changed the relation to :line_items
Class Product < ActiveRecord::Base
  belongs_to :invoice
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :products
  # The following then does not make sense
  ##has_many :invoices, :through => :invoices
end

这篇关于的has_many:经过使用,操作简单,初学者的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆