【问题标题】:Rails 3 - Model association (composition) and method delegationRails 3 - 模型关联(组合)和方法委托
【发布时间】:2012-09-09 07:44:57
【问题描述】:

我有以下模型和关联:

class JuridicalPerson < ActiveRecord::Base
end

class Supplier < ActiveRecord::Base
  belongs_to :juridical_person
  delegate  :company_name, :company_name=, :to => jurirical_person
end

控制者是:

def new
  @supplier = Supplier.new                                                                                                                                                 

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @supplier }
  end
end

架构如下所示:

create_table "suppliers", :force => true do |t|
  t.integer  "juridical_person_id"
  ...
end

create_table "juridical_people", :force => true do |t|
  t.string   "company_name"
  ...
end

现在当我尝试在视图中渲染它时,我收到以下错误:

Supplier#company_name 委托给 juridical_person.company_name,但 juridical_person 为零: #(Supplier id: nil, juridical_person_id: nil, created_at: nil, updated_at: nil)

提取的源代码(第 9 行附近):

8:       <%= f.label :company_name, "Company Name" %>
9:       <%= f.text_field :company_name %>

似乎在委派时没有创建关联的 juridical_person,但我不知道为什么。即使我在控制器中创建它,出于同样的原因尝试更新时应用程序也会中断。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails model delegation model-associations


    【解决方案1】:

    删除=更改

    delegate  :company_name, :company_name=, :to => jurirical_person
    

    delegate  :company_name, :company_name, :to => jurirical_person
    

    【讨论】:

    • 为什么要留下两个 company_name 委托?顺便说一句,没用,但谢谢。
    【解决方案2】:
    class JuridicalPerson < ActiveRecord::Base
        has_many :suppliers
    end
    

    【讨论】:

    • 我看不到逻辑,因为我没有从 JuridicalPerson 类访问供应商集合。反正我试过了,还是不行,谢谢。
    • 是的,实际上您的问题是您正在尝试为尚未创建的 juridical_person 设置 company_name。您可能需要查看 Accepts_nested_attributes_for railscasts.com/episodes/196-nested-model-form-revised
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多