rails中的特定模型关联案例

时间:2015-04-04 10:07:17

标签: ruby-on-rails forms associations

我有3个表:提案,项目/提案(项目嵌套在提案中)和发票。

我想为获得批准的提案中的这些项目创建发票。这些协会如何看起来像?另外,我如何设置发票表单以仅选择那些得到客户批准的项目?

1 个答案:

答案 0 :(得分:1)

考虑为Proposal和Invoice创建两个不同的订单项模型。

class Proposal < ActiveRecord::Base
  has_many :proposal_line_items
end

class ProposalLineItem < ActiveRecord::Base
  belongs_to :proposal
end

class Invoice < ActiveRecord::Base
  has_many :invoice_line_items
end

class InvoiceLineItem < ActiveRecord::Base
  belongs_to :invoice
end

您可以考虑批准&#34;&#34;提案订单项中的属性。在发票表单中,您可以显示客户批准的提案订单项。

为Proposal和Invoice提供单独的订单项的建议基于ERP数据建模原则,以维护Invoice的完整性。

<强>更新

例如,以下是建议模型的示例迁移

class CreateProposalLineItems < ActiveRecord::Migration
  def change
    create_table :proposal_line_items do |t|
      t.references :proposal, index: true, foreign_key: true
      t.string :name
      t.integer :approved

      t.timestamps null: false
    end
  end
end

class CreateProposals < ActiveRecord::Migration
  def change
    create_table :proposals do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

class InvoicesController < ActionController
  def new
    @approved_items = Proposal.find(params[:proposal_id]).proposal_line_items.where(:approved => 1)
  end
end

您可以在视图中迭代@approved_items并将其显示给用户。

V