如何显示只连接到单个用户的记录?

问题描述 投票:0回答:2

我希望你能在这里帮助我。

我希望用户只能够看到他们被分配到的课程的预约。我如何设置它在控制器?

我有3个模型。

class Appointment < ActiveRecord::Base  
  belongs_to :user
  belongs_to :course
end

class User < ActiveRecord::Base  
  has_many :courses, :through => :assignments
  has_many :appointments
end

class Course < ActiveRecord::Base
  has_many :users, :through => :assignments
  has_many :appointments
end
associations ruby-on-rails-3 devise
2个回答
2
投票

你应该就可以了。

@appointments = current_user.appointments

还是我在你的问题中遗漏了什么?


编辑一下。 一个更详细的例子。

在你的控制器中(比如说是AppointmentsController)。

class AppointmentsController < ApplicationController

  def index
    @appointments = current_user.appointments
  end

end

然后,在相应的视图(appointmentsindex.html.erb)中:

<%- @appointments.each do |appointment| -%>
  <%= appointment.name %>
<%- end -%>

这一切都基于你有current_user可用的假设, 但由于你已经用 "devise "标记了问题,我假设你有。


0
投票

我想补充一下idlefingers的回答,你应该重新检查课程和用户之间的关系。两边都有has_many似乎有点奇怪。使用has_many_and_belongs_to。

© www.soinside.com 2019 - 2024. All rights reserved.