Reputation: 177
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 %>
Upvotes: 0
Views: 241
Reputation: 12578
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.
Upvotes: 0
Reputation: 4420
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
Upvotes: 0
Reputation: 9701
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.
Upvotes: 1