2014-03-13 94 views
1

我有这个在我的config/routes.rb为什么我得到一个NoMethodError呢?

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表已经用数据填充。

当我输入一个URL,看起来像这样:

http://localhost:3000/football/south_west 

我得到了下面的错误消息: undefined method ``title' for nil:NilClass我已经意识到这两个@region@category正在返回零,但我不明白为什么。我确实有一个football标题的类别和south_west分别在类别和地区表中的标题。

+0

请指定错误来自的文件和行号 – MikeZ

+1

我们不能帮助你基于什么你已经发布。你真正的问题是“为什么不是我的地区/类别被发现?”而且你还没有发布任何可以帮助我们告诉你的东西。打开导轨控制台并确保可以找到记录。 – meagar

+0

@meagar当我运行rails控制台时,我可以获得区域和类别。例如当我这样做:category = Category.where(title:'football')。first:I get Category Load(31.2ms)SELECT categories'。* FROM categories WHERE categories.title ='football'ORDER BY title LIMIT 1 = >#<分类id:12,标题:“football”,created_at:“2013-04-19 10:47:07”,updated_at:“2013-05-26 18:43:46”>' –

回答

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

+0

我已经试过find_by但它仍然不工作,我已经意识到问题不是查询没有找到任何记录,但查询没有被解雇。当我检查服务器日志时,应用程序只是呈现视图而不尝试查找“@ category”,“@ region”或“@ teams” –

+0

非常奇怪。你确定它正在触发该控制器的操作?可能是你的路线问题? –

+0

非常感谢,我犯了一个粗心的错误,就是没有关闭'filtered_by_region'方法之上的方法。因此,应用程序可能无法找到该操作,因此在不触及操作的情况下渲染视图。你的建议很有帮助。 –

相关问题