How to do this sql statement using Rails
I have two models as follows:
icon.rb
belongs_to :category
attr_accessible :name, :url, :category_id, :icon_for
# == Schema Information
#
# Table name: icons
# id :integer not null, primary key
# name :string(255)
# 开发者_如何学Pythonurl :string(255)
# category_id :integer
# icon_for :string(255)
category.rb
has_many :icons
attr_accessible :name, :adult
end
# == Schema Information
#
# Table name: categories
#
# id :integer not null, primary key
# name :string(255)
In the Icons controller
def index
@icons = Icon.where(:icon_for => params[:icon_for])
@category_names_for_icons = ???????
end
I want to get all the category names for the categories the selected icons are for.
category_names = Category.where(:id => @icons.category_id) how to make this a range?
Am I on the right track?
You want to extract the category_id from each of your @icons into an array:
category_names = Category.where(:id => @icons.map(&:category_id))
The Ruby map
function iterates over an array, and returns an array. You can think of the &:category_id
bit as calling the category_id function on each item in the array.
精彩评论