【问题标题】:Rails 5, Concerns - how to use methods in a formRails 5,关注点 - 如何在表单中使用方法
【发布时间】:2016-11-01 01:09:11
【问题描述】:

我正在尝试学习如何在我的 Rails 5 应用中使用模型关注点。

我有一个嵌套模型:

class Stance::Cost < ApplicationRecord

    include HasCostPolicy

    belongs_to :organisation, inverse_of: :cost

在我的模型/关注文件夹中,我有:

module HasCostPolicy
  extend ActiveSupport::Concern
  included do
    enum cost_sharing: {
                    proportionately: 1,
                    equally: 2,
                    no_contribution: 3,
                    bear_all_costs: 4,
                    other_cost_policy: 5

                  }
    end
end

然后在我的成本嵌套形式中,我有:

<%= f.input :ip_expenses, as: :select, label: "Responsibility for IP expenses", collection: Stance::Cost.cost_sharing.map { |key, val| [key.humanize, key] } %> 

当我尝试呈现组织表单(使用嵌套成本字段)时,我收到一条错误消息:

undefined method `cost_sharing' for #<Class:0x007ffe7eaef220>

我需要做什么才能在我的嵌套表单中使用 HasCostPolicy 关注点?

【问题讨论】:

  • Stance::Cost.cost_sharing 是否在 rails 控制台中定义?
  • @maxpleaner - 没有。 c = Stance::Cost.new => #<:cost id: nil organization_id: ip_expenses: ip_note: dialect_expenses: duty_note: created_at: updated_at:> 2.3。 1p112 :009 > c.cost_sharing = 1 NoMethodError: #<:cost:0x007f9c5e7f28d8> 的未定义方法 `cost_sharing='

标签: ruby-on-rails ruby activesupport-concern


【解决方案1】:

奇怪的是,我需要在表单中复数 cost_sharing。

我不明白为什么,但这有效:

<%= f.input :ip_expenses, as: :select, label: "Responsibility for IP expenses", collection: Stance::Cost.cost_sharings.map { |key, val| [key.humanize, key] } %> 

【讨论】:

  • 在类 (Stance::Cost) 上定义了复数方法,并返回包含所有可能值的散列。但在实例 (Stance::Cost.new) 上,定义了单数,并返回一个字符串。
  • 我不明白这是什么意思。该方法在关注点中未定义为复数形式。枚举定义为“cost_sharing”(单数)。
  • 是的,rails 为您的课程创建了复数方法。
  • 我只是不明白你的意思。如果我将枚举定义为单数,您的意思是rails会自动将其转换为复数吗?
  • 我没有使用过多的 enuns,但这似乎正在发生。无论如何,我不会感到非常惊讶,rails 经常使用复数 / 驼峰式 / 下划线的技巧
猜你喜欢
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
相关资源
最近更新 更多