1

我正在尝试创建一个显示多个一对多关联的视图。在我的应用程序中,每个“检查”分配给一个“客户”和“代理”。我已经建立了我的关系。代理正在返回,但是客户返回一个未定义的方法nil:nilClass代表“name”。未定义的方法 - 多个belongs_to关联

# inspections_controller.rb 

    def new 
     @inspection = Inspection.new 
     @agents = Agent.all 
     @clients = Client.all 

     respond_to do |format| 
      format.html # new.html.erb 
      format.json { render json: @inspection } 
     end 
    end 

# inspection.rb (model) 

    belongs_to :agent 
    belongs_to :client 

# agent.rb (model) 

    has_many :inspections 

# client.rb (model) 

    has_many :inspections 

# index.html.erb (inspections view) 

    <td><%= inspection.agent.name %></td> # works 
    <td><%= inspection.client.name %></td> # returns undefined method `name' 

我在这里亏本,因为关联和表格的设置完全一样。我能够返回<%= inspection.client_id %>就好。

回答

0

您可能没有具有client_id的检查记录的相应客户端。也许你在某个时候手动删除了一个客户端?检查你的数据,并添加检查你的代码,以确保您不会引发错误所以像这可能帮助

<td><%= inspection.client.name unless inspection.client.blank?%></td> # returns undefined method `name' 

至少你就能得到一个视觉的想法,其中检查不要这样没有相应的客户使您更容易调查为什么这可能是

+0

非常感谢。这正是问题所在。作为新手,Rails试图返回一个没有客户关联的检查。在except语句中添加允许我在需要的地方有空记录。 –

相关问题