简体   繁体   中英

undefined method for nil:NilClass error

I'm receiving an undefined method `site_name' for nil:NilClass error for the following. 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.

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.

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" . And then you simply define it on nil:

def nil.site_name
  "Example.com"
end

And the error will go away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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