如何将Rails一对多地关联到一对一关联?

时间:2017-07-04 15:57:15

标签: ruby-on-rails associations

用户模型has_many公司和公司属于用户。

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

user.rb

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

company.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并在我的公司#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,还是我?

任何人都可以帮助我解决我出错的地方吗?谢谢。

1 个答案:

答案 0 :(得分:1)

  

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

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

@company = current_user.company.new(company_params)

应该是

@company = current_user.build_company(company_params)

以下是has_one关联

的所有available methods的列表