Rails无法在显示视图中查看关联的模型详细信息

时间:2012-12-03 05:06:22

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个展示视图:

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

它产生了这个:

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">] 

但如果我这样做:

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

我收到错误:

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

为什么我会收到此错误?

模型如下

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

控制器的show动作:

# 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

3 个答案:

答案 0 :(得分:1)

这里Application有很多ApplicationField。例如,一个应用程序有3个 application_field。如果您放置application.application_field,它将收集所有3个application_field记录并保留在一个数组中。因此,如果您放置@ application.application_field.field_name,它将为An ARRAY抛出未定义的方法`field_name'。

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

答案 1 :(得分:1)

@application.application_field.first.field_name

...应该为你提供实际的对象。

答案 2 :(得分:1)

您可以按如下方式编写模型:
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`

现在 Application 对象显然会收集 application_fields

现在您可以在节目页面中显示如下:

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