我想知道是否有一种方法可以通过删除下面的至少一个条件或删除confirmations.each do块代码来实现我的代码目标。这感觉就像has_many :through协会强迫我做这个笨拙的代码,但我认为我很可能是以错误的方式做事情。
在下面的代码中,我们使用的是views/appointments/show.html.erb
基本上,如果用户已经确认他们正在参加约会,我想给他们一个取消确认的选项。第一个if语句检查他们是否确认出席。
由于用户可能已经在多个约会中确认了出勤情况,所以我会循环查看用户的所有确认,这就是confirmations.each do代码的原因。
然后,我必须创建delete链接来确认这个@任命,因此在第二个if语句中,我比较了确认的appointment_id,以确保确认的appointment_id与我们所在页面的@appointment.id相同。
<% 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
has_many :confirmations
has_many :appointments, through: :confirmationsConfirmation.rb
belongs_to :appointment
belongs_to :userAppointment.rb
has_many :confirmations
has_many :users, through: :confirmations发布于 2013-10-03 20:13:52
如果用户尚未确认,这将获取@appointment和current_user或零的确认。
<% 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 %>您应该考虑将查询逻辑移除到范围或模型方法。
https://stackoverflow.com/questions/19168142
复制相似问题