Rails 3 中的嵌套属性 [英] Nested Attributes in Rails 3
问题描述
谁能帮我介绍一下 Rails 3 中的嵌套属性?
我有两个模型:证书和托管人,相关如下:
证书模型:
班级证书
证书控制器:
class CertificateController <应用控制器定义问题@certificate = Certificate.new@certificate.custodian.build结尾结尾
我的观点:
<% form_for(:certificate, :url => {:action => 'testing'}) do |f|-%><div id="错误"><%= f.error_messages %>
<%= f.label :number, "证书编号" %><%= f.text_field :number %><br/><%= f.label :num_of_shares, "共享数量" %><%= f.text_field :num_of_shares %><br/><% f.fields_for :custodian do |custodian|-%><%= custodian.label :name, "保管人姓名" %><%= custodian.text_field :name %><%结束-%><%= f.submit "颁发证书", :disable_with =>'工作....' %><%结束-%>
现在,出于某种原因,在我的控制器第 4 行:@certificate.custodian.build
我收到此错误:undefined method 'build' for nil:NilClass
有人可以帮忙吗?
accepts_nested_attributes_for 应该站在一对多关系的一方.
class Custodian <ActiveRecord::Basehas_many : 证书accepts_nested_attributes_for :certificates结尾
因此,在您看来,应该没有 fields_for :custodian,这是错误的一面.如果您必须从该视图构建证书,则必须列出可用的托管人,可能在选择框中.
can anyone please walk me through Nested Attributes in Rails 3?
I have two Models: Certificates and Custodians, related as follows:
Certificate Model:
class Certificate < ActiveRecord::Base
belongs_to :shareholder
belongs_to :custodian
belongs_to :issuer
accepts_nested_attributes_for :custodian, :shareholder, :issuer
end
Certificate Controller:
class CertificateController < ApplicationController
def issue
@certificate = Certificate.new
@certificate.custodian.build
end
end
My View:
<% form_for(:certificate, :url => {:action => 'testing'}) do |f| -%>
<div id="error">
<%= f.error_messages %>
</div>
<%= f.label :number, "Certificate Number" %>
<%= f.text_field :number %> <br/>
<%= f.label :num_of_shares, "Number Of Shares" %>
<%= f.text_field :num_of_shares %> <br/>
<% f.fields_for :custodian do |custodian| -%>
<%= custodian.label :name, "Custodian Name" %>
<%= custodian.text_field :name %>
<% end -%>
<%= f.submit "Issue Certificate", :disable_with => 'Working....' %>
<% end -%>
Now, for some reason, in my controller on line 4: @certificate.custodian.build
I'm getting this error: undefined method 'build' for nil:NilClass
Can any one please help?
accepts_nested_attributes_for should go on the side of one in the one-to-many relationship.
class Custodian < ActiveRecord::Base
has_many :certificates
accepts_nested_attributes_for :certificates
end
So, in your view, there should be no fields_for :custodian, it's on the wrong side. If you have to build a certificate from that view, you have to list custodians available, probably in a select box.
这篇关于Rails 3 中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!