我试图在提供的视图(profiles_controller.rb)中显示UserLesson.where(user_id:current_user_id)的数量。目前它显示的是UserLesson总数而不是单个用户。 以下是我的观点:
<% @user.lectures.each do |lecture| %>
<div class="col-md-4 margin-s mb-60">
<div class="lecture-box">
<%= image_tag lecture.picture.url(:medium) %>
<%= lecture.lessons.size %>
<%= lecture.lessons.total_lesson %> #SHOULD BE HERE
<p class="pad5"><%= truncate(lecture.description, length: 80) %> </p>
<%= link_to "Start Now", lecture, class: "btn btn-primary" %>
</div> <!-- .lecture-box -->
</div> <!-- .col-md-4 -->
<% end %>
这是我的课程.rb:
class Lesson < ActiveRecord::Base
has_one :lecture, through: :chapter
belongs_to :chapter
has_many :user_lessons
def self.total_lesson
Lesson.joins(:user_lessons).size
end
end
其他型号:
class UserLesson < ActiveRecord::Base
belongs_to :user
belongs_to :lesson
# validates_uniqueness_of :user_lesson, :scope => [:user, :lesson]
end
class Lesson < ActiveRecord::Base
has_one :lecture, through: :chapter
belongs_to :chapter
end
class User < ActiveRecord::Base
has_many :enrollments
has_many :user_lessons
has_many :lectures, through: :enrollments
accepts_nested_attributes_for :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
validates :lecture, uniqueness: { scope: :user, message: "should happen once per user" }
end
class Lecture < ActiveRecord::Base
belongs_to :category
has_many :lessons, through: :chapters, dependent: :destroy
has_many :chapters
belongs_to :teacher
# For course user relationship
has_many :enrollments
has_many :users, through: :enrollments
accepts_nested_attributes_for :enrollments
accepts_nested_attributes_for :chapters
端
class Chapter < ActiveRecord::Base
has_many :lessons
belongs_to :lecture
accepts_nested_attributes_for :lessons
end
答案 0 :(得分:0)
由于您的视图中有@user
(即current_user),因此您只需在视图中调用以下内容即可获得此用户的课程总数:< / p>
Lesson.joins(:user_lessons).where('user_lessons.user_id = ?', @user.id).count
要获得此演讲的课程总数:
Lesson.joins(:user_lessons).joins(:lectures).where('user_lessons.user_id = ? AND lectures.id = ?', @user.id, lecture.id).count
其中lecture
是您视图文件中的本地变量。
您应该可以直接在视图中调用此方法以获得所需的计数。
答案 1 :(得分:0)
要查找属于与当前用户相关的讲座的课程数量,您可以执行此操作
<%= lecture.lessons.select{ |l| l.users.inculde? current_user }.count %>
但您必须将其添加到Lesson.rb
:
has_many :users, through: :user_lessons