Haml / Rails 4:条件-里面重复代码
Haml / Rails 4: Conditions - repeating code inside
如何使用 haml/rails 制作类似的东西:
- if current_user.is_seeking_job == true && current_user.is_seeking_contract == true
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort < ?", 2).limit(10).each do |job|
- else
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort > ?", 1).limit(10).each do |job|
%li
显然我得到了一个错误,因为我在第一个循环中没有代码。
问题是我有不止这两个条件,%li
里面有很多代码。
当然我可以针对每个条件复制它并且它会起作用,但是如何在不一遍又一遍地复制同一段代码的情况下做到这一点?
在此先感谢您的帮助!
您可以执行以下操作:
- if current_user.is_seeking_job && current_user.is_seeking_contract
- sort_order = "sort < ?"
- sort_param = 2
- else
- sort_order = "sort > ?"
- sort_param = 1
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where(sort_order, sort_param).limit(10).each do |job|
但是,此解决方案违反了 separation of concerns principle - 您的视图应该(理想情况下)仅显示数据,而不查询数据库。我建议将查询和相关逻辑移动到更合适的地方,例如模型方法或范围。
如何使用 haml/rails 制作类似的东西:
- if current_user.is_seeking_job == true && current_user.is_seeking_contract == true
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort < ?", 2).limit(10).each do |job|
- else
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort > ?", 1).limit(10).each do |job|
%li
显然我得到了一个错误,因为我在第一个循环中没有代码。
问题是我有不止这两个条件,%li
里面有很多代码。
当然我可以针对每个条件复制它并且它会起作用,但是如何在不一遍又一遍地复制同一段代码的情况下做到这一点?
在此先感谢您的帮助!
您可以执行以下操作:
- if current_user.is_seeking_job && current_user.is_seeking_contract
- sort_order = "sort < ?"
- sort_param = 2
- else
- sort_order = "sort > ?"
- sort_param = 1
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where(sort_order, sort_param).limit(10).each do |job|
但是,此解决方案违反了 separation of concerns principle - 您的视图应该(理想情况下)仅显示数据,而不查询数据库。我建议将查询和相关逻辑移动到更合适的地方,例如模型方法或范围。