我有这个在我的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
我也相应regions
,teams
和categories
表已经用数据填充。
当我输入一个URL,看起来像这样:
http://localhost:3000/football/south_west
我得到了下面的错误消息: undefined method ``title' for nil:NilClass
我已经意识到这两个@region
和@category
正在返回零,但我不明白为什么。我确实有一个football
标题的类别和south_west
分别在类别和地区表中的标题。
请指定错误来自的文件和行号 – MikeZ
我们不能帮助你基于什么你已经发布。你真正的问题是“为什么不是我的地区/类别被发现?”而且你还没有发布任何可以帮助我们告诉你的东西。打开导轨控制台并确保可以找到记录。 – meagar
@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”>' –