2012-12-03 104 views
0

我有這個節目的看法:的Rails不能查看相關的模型細節顯示視圖

<%= @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 

回答

1

這裏的應用有很多ApplicationField。例如,一個應用程序具有3個應用程序字段。如果你把application.application_field它會收集所有的3 application_field記錄並保存在一個數組中。所以,如果你把@ application.application_field.field_name它會拋出一個未定義的方法`field_name'ARRAY。

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

稀釋是謝謝你。一個簡單的for循環將幫助我很好地實現這一點。 – Catfish

+0

謝謝你鮎魚:D – vijikumar

1
@application.application_field.first.field_name 

...應該讓你的實際對象。

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_fields的集合。

現在可以顯示在顯示頁面如下:

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