为什么我会收到NoMethodError?

时间:2014-03-13 18:43:07

标签: ruby-on-rails ruby activerecord rails-routing

我在config/routes.rb

中有这个
get '/:category/:region', to: 'categories#filtered_by_region'

filtered_by_region操作如下所示:

#filtered_by_region method
def filtered_by_region
  @region = Region.where(title: params[:region]).first
  @category = Category.where(title: params[:category]).first
  @teams = Team.where(region_id: @region.id, category_id: @category.id)
end

我的视图filtered_by_region.html.erb如下所示:

Region: <%= @region.title %>
Category: <%= @category.title %>

<% @teams.each do |team|%>
  <%=team.title %>
<% end %>

region.rb模型如下:

class Region < ActiveRecord::Base
  has_many :teams
  attr_accessible :title
end

category.rb模型如下:

class Category < ActiveRecord::Base
  has_many :teams
  attr_accessible :title
end

team.rb模型如下所示

class Team < ActiveRecord::Base
  belongs_to :category
  belongs_to :region
end

我还有已填充数据的相应regionsteamscategories表。

当我输入一个如下所示的网址时:

http://localhost:3000/football/south_west

我收到以下消息的错误: undefined method ``title' for nil:NilClass我已经意识到@region@category都返回零但我不明白为什么。我的类别和区域表分别有football标题和south_west标题的区域。

1 个答案:

答案 0 :(得分:0)

为什么不使用find_by(如果您使用的是Rails 4)或find_by_title(如果您使用的是Rails 3):

def filtered_by_region
   @category = Category.find_by_title(params[:category])
   @region = Region.find_by_title(params[:title])

   if defined?(@category) && defined?(@region)
       @teams = Team.where(region_id: region.id, category_id: category.id)
   else
       redirect_to root_path
   end
end

我认为可能的问题可能是您的查询未找到任何记录,或者您将尝试将某个集合作为记录访问(无论是否使用.first