如何从三个模型的关系中访问一个模型的名称?
我需要在索引视图中打印出类别下某个城市的所有项目,id为2(任意数字)。到目前为止我拥有城市中所有项目的实例(如下所示),现在我想按类别过滤它们。我该怎么做?这是我在
class CategoryController < ApplicationController
def index
@city= City.find(session[:city_id])
@[email protected]
end
end
索引视图
<%[email protected] do |item|%>
<%=item.item_name%>
<%end%>
模型下面的代码
class City < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :city
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :items
end
I need to print out in the index view, all items from a certain city under category with id 2(any number).So far i have instance of all items in the city(as shown below),now i want to filter them by category.How do i do that?This is my code below
class CategoryController < ApplicationController
def index
@city= City.find(session[:city_id])
@[email protected]
end
end
index view
<%[email protected] do |item|%>
<%=item.item_name%>
<%end%>
Models
class City < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :city
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :items
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
控制器:
您应该能够执行以下操作:
或类似的操作:
查看:
Controller:
You should be able to do something like:
Or something like:
View: