【问题标题】:Specific model association case in railsrails中的具体模型关联案例
【发布时间】:2015-04-04 10:07:17
【问题描述】:

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

我想为提案中获得批准的项目创建发票。这些关联会是什么样子?另外,我将如何设置发票表单以仅选择那些得到客户批准的项目?

【问题讨论】:

    标签: ruby-on-rails forms associations


    【解决方案1】:

    考虑为提案和发票创建两个不同的订单项模型。

    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
    

    您可以考虑在提案订单项中添加“已批准”属性。在发票表单中,您可以显示客户批准的提案订单项。

    为提案和发票设置单独的行项目的建议是基于 ERP 数据建模原则,以保持发票的完整性。

    更新

    例如,这里是建议模型的示例迁移

    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

    【讨论】:

    • 您能否指导我了解如何在发票表格中仅显示客户批准的项目?谢谢V
    • 如果您按照建议创建了模型,您可以使用 p.proposal_line_items.where(:approved => 1).length 找到已批准的订单项。得到客户的认可。
    • 所以我按照建议创建了模型。我应该在哪里添加 p.proposal_line_items.where(:approved => 1).length 。这应该在发票显示视图​​中吗?
    • 我已经用一个假设更新了示例代码。您将以proposal_id 作为参数调用新方法。
    • 所以我去更改我的 InvoicesController 并发现我的说 InvoiceController
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    相关资源
    最近更新 更多