Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Attributes in Rails 3

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?

like image 320
Jasdeep Singh Avatar asked Feb 01 '11 21:02

Jasdeep Singh


People also ask

What is nested attributes rails?

Rails provide a powerful mechanism for creating rich forms called 'nested attributes' easily. This enables more than one model to be combined in forms while maintaining the same basic code pattern with simple single model form. Nested attributes allow attributes to be saved through the parent on associated records.

What are nested attributes?

Nested attributes are a way of applying sub-categories to your attributes. For instance, instead of having a single searchable attribute price , you may set up some sub-categories: price.net , price.


2 Answers

With a belongs_to, it should be

@certificate.build_custodian
like image 198
guitsaru Avatar answered Sep 23 '22 15:09

guitsaru


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.

like image 35
Srdjan Pejic Avatar answered Sep 25 '22 15:09

Srdjan Pejic