首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ids与has_many的比较:通过关联

ids与has_many的比较:通过关联
EN

Stack Overflow用户
提问于 2013-10-03 19:57:56
回答 1查看 39关注 0票数 1

我想知道是否有一种方法可以通过删除下面的至少一个条件或删除confirmations.each do块代码来实现我的代码目标。这感觉就像has_many :through协会强迫我做这个笨拙的代码,但我认为我很可能是以错误的方式做事情。

在下面的代码中,我们使用的是views/appointments/show.html.erb

基本上,如果用户已经确认他们正在参加约会,我想给他们一个取消确认的选项。第一个if语句检查他们是否确认出席。

由于用户可能已经在多个约会中确认了出勤情况,所以我会循环查看用户的所有确认,这就是confirmations.each do代码的原因。

然后,我必须创建delete链接来确认这个@任命,因此在第二个if语句中,我比较了确认的appointment_id,以确保确认的appointment_id与我们所在页面的@appointment.id相同。

代码语言:javascript
复制
<% if current_user.confirmations.map(&:appointment_id).include?(@appointment.id) %>

<% current_user.confirmations.each do |confirmation| %>
<% if confirmation.appointment_id == @appointment.id %>

<%= link_to "delete", confirmation_path(confirmation), method: :delete,
                                  data: { confirm: "You sure?" } %> 

<% end %>
<% end %>
<% end %>

User.rb

代码语言:javascript
复制
 has_many :confirmations
 has_many :appointments, through: :confirmations

Confirmation.rb

代码语言:javascript
复制
belongs_to :appointment
belongs_to :user

Appointment.rb

代码语言:javascript
复制
has_many :confirmations
has_many :users, through: :confirmations
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-03 20:13:52

如果用户尚未确认,这将获取@appointmentcurrent_user或零的确认。

代码语言:javascript
复制
<% confirmation = @appointment.confirmations.find_by_user_id(current_user.id) %>
<% if confirmation %>
  <%= link_to "delete", confirmation_path(confirmation), method: :delete,
                                    data: { confirm: "You sure?" } %> 
<% end %>

您应该考虑将查询逻辑移除到范围或模型方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19168142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档