加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 通过关系在has_many中找到唯一记录的更好方法

发布时间:2020-12-17 03:56:48 所属栏目:百科 来源:网络整理
导读:在我的rails应用程序中,用户可以参加活动 – user.rb has_many :attendanceshas_many :events,through: :attendances event.rb has_many :attendanceshas_many :users,through: :attendances …有一个由event_id,user_id和其他一些零碎组成的考勤表 – atten
在我的rails应用程序中,用户可以参加活动 –

user.rb

has_many :attendances
has_many :events,through: :attendances

event.rb

has_many :attendances
has_many :users,through: :attendances

…有一个由event_id,user_id和其他一些零碎组成的考勤表 –

attendance.rb

belongs_to :user
belongs_to :writers_event

在寻找特定的出勤时,我发现自己正在使用.where … .first – 例如

attendance = Attendance.where(user_id: @user.id,event_id: this_event_id).first

我觉得我错过了在这种情况下我们谈到使用像find_by这样的东西的课程 – 换句话说,你确信你正在寻找独特的东西.这可能并不重要,但是搜索一个集合然后从中获取第一个对象会感到浪费和错误.

有没有更好的办法?

我环顾四周,这是最接近的,但不(我认为)真的覆盖它. How to display unique records from a has_many through relationship?

解决方法

您可以使用find_by:

attendance = Attendance.find_by(user_id: @user.id,event_id: this_event_id)

虽然在幕后,它正在进行查找并采取第一个.

但是,您可以从rails获得更多帮助:

current_user.attendances.find_by(event_id: this_event_id)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读