2 ruby activerecord ruby-on-rails rails-models
好吧,我知道这是对萨斯当然,人们一直在问有关那还有问题,但我花了很多时间试图与阅读和我被困.首先,当你有一个叫做电影模式,是它更好地使用评级为模型,并将其关联或只是保持在一个阵列的浮动空间等级(!).其次,这是我现在在控制器中的内容:
def index
@movies = Movie.where(params[:ratings].present? ? {:rating => (params[:ratings].keys)} : {}).order(params[:sort])
@sort = params[:sort]
@ratings = Ratings.all
end
Run Code Online (Sandbox Code Playgroud)
现在,我决定创建一个评级模型,因为我认为它会更好.这是我的观点:
= form_tag movies_path, :method => :get do
Include:
- @ratings.each do |rating|
= rating.rating
= check_box_tag "ratings[#{rating.rating}]"
= submit_tag "Refresh"
Run Code Online (Sandbox Code Playgroud)
我尝试了一些与在复选框标签内使用条件三元组相关的所有内容,以".include?(评级)结尾?"真:""我尝试了所有应该工作的但却没有.我不想要确切的答案,我只需要指导.谢谢!
更新(控制器的方法):
这是我的控制器中读取此哈希的索引方法 - 为清楚起见.我为之前的模糊道歉.
def index
@all_stores = Product.all_stores
@selected_stores = params[:stores] || session[:stores] || {}
if @selected_stores == {}
@selected_stores = Hash[@all_stores.map {|store| [store, store]}]
end
if params[:stores] != session[:stores]
# session[:stores] = @selected_stores
session[:stores] = params[:stores]
redirect_to :stores => @selected_stores and return
end
@products = Product.order("created_at desc").limit(150).find_all_by_store(@selected_stores.keys).group_by { |product| product.created_at.to_date}
. . . etc
Run Code Online (Sandbox Code Playgroud)
hou*_*se9 11
几件事
1).order(params[:sort])打开你的sql注入攻击,有人可能会通过将其放入查询字符串中删除所有用户
http://localhost:3000/movies?sort=email%3B+DELETE+from+users+--
看看rails 3 activerecord命令 - 什么是正确的sql注入工作?,这个问题不存在.where,rails将清理where方法的输入
2)次要的事情,AREL会延迟对数据库进行实际调用,直到您对集合进行迭代,这样您就可以"构建"查询,这种语法可能更容易理解,然后使用三元运算符?
@movies = Movie.order(xxxxxx)
@movies = @movies.where(:rating => params[:ratings].keys) if params[:ratings].present?
Run Code Online (Sandbox Code Playgroud)
3)对于你的评级,像cdesrosiers说恒定是好的,那么你的观点
Movie::RATINGS.each do |rating|
check_box_tag "ratings[]", rating # <input type="checkbox" name="ratings[]" value="PG" />
Run Code Online (Sandbox Code Playgroud)
编辑:维护选定的值
# controller
@selected_ratings = (params[:ratings].present? ? params[:ratings] : [])
# view
Movie::RATINGS.each do |rating|
check_box_tag "ratings[]", rating, @selected_ratings.include?(rating)
# <input type="checkbox" name="ratings[]" value="PG" checked="checked" />
Run Code Online (Sandbox Code Playgroud)
注意复选框命名中的[],这将为你的控制器动作提供params [:ratings]作为一个数组
@movies = @movies.where("rating IN (?)", params[:ratings]) if params[:ratings].present? and params[:ratings].any?
Run Code Online (Sandbox Code Playgroud)
一些链接
| 归档时间: |
|
| 查看次数: |
8507 次 |
| 最近记录: |