【问题标题】:How to use symbol to call active record search如何使用符号调用活动记录搜索
【发布时间】:2018-08-28 11:43:02
【问题描述】:

首先,请原谅这个糟糕的标题。我知道我想解决什么,但我认为我没有正确的语言来充分描述问题。

我有一个数据库,其中每门教学课程都可以属于“教科书”或“有针对性”的教学风格。目前,我根据用户的选择将这些信息(教科书或定向)保存在 cookie 中。

我提取此信息,并根据值搜索与教科书或目标 ID 相关的记录。

目前我有以下代码:

case coursetype
  when "textbook"
    activecourses = Course.find(topicid).textbook_children.where(active: true).order(:id)
    @lessons = Video.joins(:textbook_parent).where('courses.id' => activecourses.pluck(:id)).order(:id)
  else
    activecourses = Course.find(topicid).targeted_children.where(active: true).order(:id)
    @lessons = Video.joins(:targeted_parent).where('courses.id' => activecourses.pluck(:id)).order(:id)
 end

这不是很干。

我基本上想写:

activecourses = Course.find(topicid).targeted_children.where(active: true).order(:id)

targeted_childrentextbook_children 是某种形式的文本字符串,它会变成一个符号(如果正确的话),但不知道该怎么做。

任何帮助将不胜感激。

如果我还没有说清楚,我很抱歉。

PS。我自学了很多 ruby​​ 和 rails。我确信代码可以用更好的方式编写……我愿意与可以帮助我改进的人一起工作……但是……请不要评判!

【问题讨论】:

    标签: ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    在您引用符号或字符串的任何地方,您都可以将其替换为包含符号或字符串的变量。

    parent_type = (coursetype == 'textbook' ? :textbook_parent : :targeted_parent)
    activecourses = Course.find(topicid).textbook_children.where(active: true).order(:id)
    @lessons = Video.joins(parent_type).where('courses.id' => activecourses.pluck(:id)).order(:id)
    

    【讨论】:

    • 感谢您的评论。由于我已经在使用.to_sym,所以我讨论过用@lessons 省略代码行。但是你在那里为我清理了一些东西!我的问题是我想用动态创建的文本替换activecourses 行中的.textbook_children。很抱歉造成混乱!
    • 所以你可以用method = :textbook_children代替Course.find(topicid).textbook_children.where...然后Course.find(topicid).send(method).where...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 2012-10-30
    相关资源
    最近更新 更多