简体   繁体   English

未定义的方法,用于nil:NilClass错误

[英]undefined method for nil:NilClass error

I'm receiving an undefined method `site_name' for nil:NilClass error for the following. 我收到以下内容的nil:NilClass错误的未定义方法`site_name' Would appreciate any help. 将不胜感激。 I'm trying to list the site_name in the Site table and i'm not sure how best to resolve the issue. 我正在尝试在“站点”表中列出site_name,但不确定如何最好地解决该问题。

class Site < ActiveRecord::Base
      attr_accessible :site_id, :site_name, :region

      has_many :trials, :foreign_key => "site_id"

    end

    class Trial < ActiveRecord::Base
      attr_accessible :trial_id, :site_id, :year, :trial_type

      scope :year, ->(year) { where(year: year) }
      scope :trial_id, ->(trial_id) { where(trial_id: trial_id) }

      belongs_to :site

    end

My Controller: 我的控制器:

class TrialsController < ApplicationController

  def index
    @years = Trial.group('year').order('year DESC')
    end

  def trial
    @trial = Trial.trial_id(params[:trial_id])
  end

**def list
@list = Trial.year(params[:year]).order(:region_id).joins(:sites).where('sites.site_id' => :site_id)

end** 结束**

end

My view: 我的观点:

    <% @list.each do |list| %>
        <tr>
        <td>
      <%= link_to list.site.site_name, trial_trials_path(trial_id: list.trial_id) %>
        </td>
        <td>    
        <%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %>
        </td>
        <td>    
        <%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) %>
        </td>
        <td>    
        <%= link_to list.planted_at, trial_trials_path(trial_id: list.trial_id) unless list.planted_at.blank? %>
        </td>
        <td>    
        <%= link_to list.picked_at, trial_trials_path(trial_id: list.trial_id) unless list.picked_at.blank? %>
        </td>
        </tr>
        <% end %>

What if you just change the line to this: 如果仅将行更改为此:

<%= link_to list.site.site_name, trial_trials_path(trial_id: list.trial_id) if list.site.try(:site_name) %>

Also, you could do a Site.where(site_name: nil) in the Rails console to see which site doesn't have a name. 另外,您可以在Rails控制台中执行Site.where(site_name: nil) ,以查看哪个站点没有名称。

if you don't want page crush even if there is not site for list, you could try to use this 如果即使没有列表站点也不想页面粉碎,则可以尝试使用此方法

list.site.try(:site_name)

but I think that you should use another flow, like 但我认为您应该使用另一种流程,例如

  1. Do not let to create list without site. 不要在没有网站的情况下创建列表。
  2. Do not list lists without sites. 不要列出没有网站的列表。

You have to decide about your default site name, eg. 您必须确定默认站点名称,例如。 "Example.com" . "Example.com" And then you simply define it on nil: 然后只需在nil上定义它:

def nil.site_name
  "Example.com"
end

And the error will go away. 错误将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM