Rails 3 Nested Models unknown attribute Error

rgoraya picture rgoraya · Jul 27, 2011 · Viewed 9.4k times · Source
  • I have a model "Issue" and a nested Model "Relationship"
  • In the issue.rb I have mentioned:

    has_many :relationships, :dependent => :destroy
    accepts_nested_attributes_for :relationships, :allow_destroy => true
    
  • In relationship.rb I have mentioned:

    belongs_to :issue
    
  • Following Ryan Bates Railcast#196 I have the following in my issues_controller:

    relationship = @issue.relationships.build
    

However, I am encountering an error "unknown attribute: relationship"

Am I doing something incorrectly here? I do see the Relationships Attributes being passed to the server in the log however, this error does not let the create to be successful.

My expertise with rails is beginners level so kindly excuse me if I am asking a question which maybe deemed trivial.

Thanks for the help.

EDIT: The relevant Controller code:

    @relationship = @issue.relationships.build
    #@relationship = Relationship.new(params[:relationship])
    if @relationship.issue_id = ''
      @relationship.issue_id = @issueid
    end

    if @relationship.cause_id = ''
      @relationship.cause_id = @issueid
    end

    @relationship.save
    redirect_to(:back, :notice => 'New Relationship was created') 

What I see on the trace:

    ActiveRecord::UnknownAttributeError in IssuesController#create
    unknown attribute: relationship

Among the Issue parameters, I see the Relationship params being passed as expected:

    "relationship"=>{"issue_id"=>"100",
    "cause_id"=>""}

ANOTHER UPDATE Posting the form_for code:

    - form_for Issue.new do |f|

      .field  
        = f.text_field :description, :class=>"formfield", :id=>"frm_descr"

      .field  
        = f.hidden_field :wiki_url, :class=>"formfield", :id=>"frm_wiki_url"

      .field
        = f.hidden_field :short_url, :class=>"formfield", :id=>"frm_img_url"

      .field
        = f.hidden_field :title, :class=>"formfield", :id=>"frm_title"         

      = f.fields_for :relationship do |builder|
        = builder.text_field :issue_id, :class=>"form_field", :id=>"frm_rel_issue_id", :value=>@issue.id 
        = builder.text_field :cause_id, :class=>"form_field", :id=>"frm_rel_cause_id"

      .actions
        = f.submit 'Create', :class=>"save_button", :name=>"save_issue_rel_button", :id=>"val_collector"

Answer

Thilo picture Thilo · Jul 27, 2011

Change this line

= f.fields_for :relationship do |builder|

to this:

= f.fields_for :relationships do |builder|

Your issue has_many relationships - plural. That will give you the correct relationships_attributes parameters.