Ruby on rails 通过关联将ID与多个进行比较
我想知道是否有办法通过删除以下至少一个条件或删除Ruby on rails 通过关联将ID与多个进行比较,ruby-on-rails,Ruby On Rails,我想知道是否有办法通过删除以下至少一个条件或删除确认。每个do块代码来实现我的代码目标。感觉像是有很多:通过关联迫使我做这种笨拙的代码,但我认为我很可能做错事了 在下面的代码中,我们使用的是views/appoints/show.html.erb 基本上,如果用户已经确认他们正在参加约会,我想给他们一个取消确认的选项。第一个if语句检查他们是否已确认出席 由于一个用户可能已确认参加了多个约会,因此我会循环浏览该用户的所有确认,这就是确认的原因 然后,我必须为@appointment确认创建删除链
确认。每个do
块代码来实现我的代码目标。感觉像是有很多:通过关联迫使我做这种笨拙的代码,但我认为我很可能做错事了
在下面的代码中,我们使用的是views/appoints/show.html.erb
基本上,如果用户已经确认他们正在参加约会,我想给他们一个取消确认的选项。第一个if
语句检查他们是否已确认出席
由于一个用户可能已确认参加了多个约会,因此我会循环浏览该用户的所有确认,这就是确认的原因
然后,我必须为@appointment确认创建删除链接,因此在第二个if
语句中,我比较确认的约会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 %>
确认.rb
belongs_to :appointment
belongs_to :user
Appointment.rb
has_many :confirmations
has_many :users, through: :confirmations
这将获取@约会
和当前用户
的确认信息,如果用户尚未确认,则获取零
<% 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 %>
您应该考虑将查询逻辑移除到范围或模型方法。
<% 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 %>