测试用户是否已在rails中有记录

时间:2016-04-06 02:59:37

标签: ruby-on-rails

我试图测试用户是否已为课程上课,如果是,请带他们去上课,否则,让他们成为新课程。该课程是课程的嵌套资源,因此我想使用:course_id来查找用户是否已经创建了课程,如果是,请将他们带到该课程。

我的尝试

    <% if current_user.lessons.course_id == (course)%>
        <td><%= link_to course.title, edit_lesson_path(:course_id) %></td>
<% end %>

(暂时没有,希望这首先发挥作用。)

老实说,任何帮助都会很棒,请告诉我是否应该添加任何内容:)

2 个答案:

答案 0 :(得分:3)

您可以使用exists?方法。以下是该方法的documentation

<% if current_user.lessons.exists?(course: course) %>

更新了解决方案

当用户积累课程时,@ toddmetheny的解决方案肯定会更快。

话虽如此,我可能会采取他的方法,但仍然使用exists?方法:

<% if Lesson.exists?(user: current_user, course: course) %>

快速基准,1000次迭代。

 # mine (first solution with a user with over 500 lessons)
 <Benchmark::Tms:0x007fc5b0ceaab8 @label="", @real=9.431750780000584, @cstime=0.0, @cutime=0.0, @stime=0.2999999999999998, @utime=7.6299999999999955, @total=7.929999999999995>

 # mine (updated solution) - Fastest
 <Benchmark::Tms:0x007fc5ab550d48 @label="", @real=8.289565541999764, @cstime=0.0, @cutime=0.0, @stime=0.3, @utime=6.7, @total=7.0>

 # toddmetheny
 <Benchmark::Tms:0x007fc5b09c5888 @label="", @real=9.237036614998942, @cstime=0.0, @cutime=0.0, @stime=0.30000000000000004, @utime=7.4, @total=7.7>

答案 1 :(得分:2)

尝试:

Lesson.where(user_id: current_user.id, course_id: course.id).count > 0