Catfish
Catfish

Reputation: 19324

Rails can't view associated model details in show view

I have a show view with this:

<%= @application.application_name %>
<%= @application.application_field %>

and it produces this:

Application name: New Employment App [#<ApplicationField id: 1, application_id: 1, applicant_id: nil, field_name: "Previous Job", field_type: "String", created_at: "2012-12-03 04:26:06", updated_at: "2012-12-03 04:26:06">, #<ApplicationField id: 2, application_id: 1, applicant_id: nil, field_name: "Previous Address", field_type: "String", created_at: "2012-12-03 04:26:06", updated_at: "2012-12-03 04:26:06">] 

but if i do:

<%= @application.application_name %>
<%= @application.application_field.field_name %>

I get the error:

undefined method `field_name' for #<ActiveRecord::Relation:0x007ff4ec822268>

Why am i getting this error?

Models are as follows

class Application < ActiveRecord::Base
    belongs_to :company
    #has_many :applicants, :through => :application_field
    has_many :application_field
    accepts_nested_attributes_for :application_field, :allow_destroy => true
    attr_accessible :application_name, :application_field_attributes
end

class ApplicationField < ActiveRecord::Base
    belongs_to :application
    has_many :application_fields_value
    #belongs_to :applicant
    attr_accessible :field_name, :field_type, :field_value, :application_field_values_attributes
    accepts_nested_attributes_for :application_fields_value, :allow_destroy => true
end

controller's show action:

# GET /applications/1
  # GET /applications/1.json
  def show
    @application = Application.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @application }
    end
  end

Upvotes: 0

Views: 181

Answers (3)

VenkatK
VenkatK

Reputation: 1305

You could have written the model as follows:
class Application < ActiveRecord::Base
   belongs_to :company

  has_many :application_fields
  accepts_nested_attributes_for :application_fields, :allow_destroy => true
  attr_accessible :application_name, :application_fields_attributes
end`

Now the Application object will obviously have collection of application_fields.

Now you can show as follows in the show page:

<%= @application.application_name %>
<%= @application.application_fields.map{|af| .field_name}.join(',') %>

Upvotes: 1

kries
kries

Reputation: 199

@application.application_field.first.field_name

...should get you the actual object.

Upvotes: 1

vijikumar
vijikumar

Reputation: 1815

Here Application has many ApplicationField. For example, one application has 3 application_field. if you put application.application_field it will collect all the 3 application_field record and keep in an array. So if you put @application.application_field.field_name it will throw undefined method `field_name' for An ARRAY.

      try with <%= @application.application_field[0].field_name %>

Upvotes: 1

Related Questions