【问题标题】:Help with rails belongs_to帮助 rails belongs_to
【发布时间】:2011-03-15 05:30:39
【问题描述】:

我被卡住了 -

我正在 Rails 中构建一个会计应用程序,并且有一个模型,其中客户将拥有多张发票以及多笔付款(与这些发票相关)

这里是一个简化模型的快速浏览:

class Customer < ActiveRecord::Base
  has_many :customer_payments
  has_many :invoices  
  accepts_nested_attributes_for :customer_payments, :allow_destroy => true
end

class CustomerPayment < ActiveRecord::Base
  has_many :customer_payment_items
  belongs_to :customer
  belongs_to :invoice
  accepts_nested_attributes_for :customer_payment_items
end

class CustomerPaymentItem < ActiveRecord::Base
  belongs_to :invoice, :inverse_of => :customer_payment_items
  belongs_to :customer_payment
end

 class Invoice < ActiveRecord::Base
  has_many :invoice_lines, :dependent => :destroy   
  has_many :customer_payment_items, :inverse_of => :invoice
  belongs_to :customer
  accepts_nested_attributes_for :invoice_lines, :allow_destroy => true
end

我有一个嵌套表单,我想在其中显示 Customer 属性、CustomerPayment 属性和 CustomerPaymentItem 属性 - 一切正常。

我还想显示每个 CustomerPaymentItem 的 Invoice 属性(每个 CustomerPaymentItem 都与单个发票相关联),虽然我可以获取一个表单来显示 CustomerPaymentItem 信息,但我无法让它显示所需的 Invoice 信息给用户参考。 - 我在从 belongs_to 关联获取数据以显示在表单上时遇到问题。

我不知所措 - 我不应该能够遍历 belongs_to 关联吗?仅供参考 - 我可以将数据发送到我知道在 CustomerPayment.new 调用期间填充发票数据的日志,它似乎只是在控制器和表单之间丢失了。

我应该如何访问这些数据?这是表单信息——(来自几个呈现的表单)未显示的内容位于 --- 之间。

<p>
  <%= f.label :amount %><br />
  <%= f.text_field :amount %>
</p>
<p>
  <%= f.label :invoice_id %><br />
  <%= f.text_field :invoice_id %>
</p>

<p>
  <% f.fields_for :invoice do |builder| %>
    --- doesn't show
    Invoice Detail
    <p>
      <%= builder.label :number %><br />
      <%= builder.text_field :number %>
    </p>  
    <p>   
      <%= builder.label :sub_total %><br />
      <%= builder.text_field :sub_total %>
    </p>
    --- doesn't show

  <% end %>
</p>

我是否在 fields_for 中遗漏了某些内容以显示 :invoice 参考数据?我的模型是否过于复杂,以至于 Rails 无法理解?

【问题讨论】:

  • 这是rails 3吗?你需要在你的 f.fields 中有一个 = 才能显示出来

标签: ruby-on-rails associations belongs-to


【解决方案1】:

@corroded 是对的 - 问题是我没有 = 登录

<% f.fields_for :invoice do |builder| %>

我想每个人都需要吸取教训

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2011-11-27
    • 2011-10-21
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多