【问题标题】:How to move a Rails one to many association to a one to one association?如何将 Rails 一对多关联移动到一对一关联?
【发布时间】:2017-12-08 04:11:51
【问题描述】:

用户模型 has_many Companies and Company belongs_to a User。

我现在想将此更改为用户 has_one Company 和 Company has_one/belongs_to 关联。我已将模型更改为如下所示:

用户.rb

class User < ApplicationRecord
    has_one :company #was has_many
    accepts_nested_attributes_for :company
    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

公司.rb

class Company < ApplicationRecord
    belongs_to  :user
    has_many        :employees, inverse_of: :company
    has_many        :quotes, inverse_of: :company
    accepts_nested_attributes_for :employees, reject_if: :all_blank, allow_destroy: true #, :reject_if => lambda { |e| e.first_name.blank? }
    accepts_nested_attributes_for :quotes, allow_destroy: true

    validates_presence_of :user, :co_name, :co_number, :postcode
    validates :co_name, length: { minimum: 2, message: "minimum of 2 chars" }
    validates :co_number, format: { with: /\A([1-9]\d{6,7}|\d{6,7}|(SC|NI|AC|FC|GE|GN|GS|IC|IP|LP|NA|NF|NL|NO|NP|NR|NZ|OC|R|RC|SA|SF|SI|SL|SO|SP|SR|SZ|ZC|)\d{6,8})\z/,
                message: "must be valid company number" }
    validates :postcode, format: { with: /\A(?:gir(?: *0aa)?|[a-pr-uwyz](?:[a-hk-y]?[0-9]+|[0-9][a-hjkstuw]|[a-hk-y][0-9][abehmnprv-y])(?: *[0-9][abd-hjlnp-uw-z]{2})?)\z/,
                message: "must be valid postcode" }

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
end

并拥有rake db:reset 并在我的 Companies#create 方法中更改了这一行:

@company = current_user.companies.new(company_params)

@company = current_user.company.new(company_params)

但我得到了一个

undefined method `new' for nil:NilClass

而且我看不出哪里出错了。 current_user 应该可用吗? has_one 关联已定义,因此我应该可以调用 company.new 对吗?我不需要将 foreign_key 添加到用户,或者我需要吗?

谁能帮我解决我哪里出错了?谢谢。

【问题讨论】:

  • 改用@company = current_user.build_company(company_params)
  • 很棒的@pavan,现在可以了,.build_company 和 `.company.new' 有什么区别,你能告诉我吗? (请在上面作为答案,我会接受。谢谢
  • 我已经添加了我的答案:)

标签: ruby-on-rails associations


【解决方案1】:

nil:NilClass 的未定义方法 `new'

对于has_one,你应该使用build_association方法,所以

@company = current_user.company.new(company_params)

应该是

@company = current_user.build_company(company_params)

这是has_one 关联的所有available methods 的列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2021-10-07
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多