从 has_many/belongs_to 关系中的另一个 table 访问特定列

accessing specific columns from another table in the has_many/belongs_to relationship

我有一个 Rsvp table,它在 UserEvent 之间形成一个连接。 Rsvp table 有 rsvp status 的信息。我需要 Event 才能在 users/show 视图中访问此信息,也许可以像下面显示的那样拨打 event.rsvp_status。用户可以随时自由更改 rsvp 状态。如何实现? 我的模型是什么样的:

class Rsvp < ApplicationRecord
  enum status: { not_interested: 0, interested: 1, attending: 2 }

  belongs_to :event
  belongs_to :user
end

class Event < ApplicationRecord
  has_many :rsvps
  has_many :users, through: :rsvps

  def title
    "#{self.name} with #{self.artists.map(&:name).join(", ")} at #{self.venue.name}"
  end
end

class User < ApplicaitonRecord
  has_many :rsvps
  has_many :events, through: :rsvps
end

我在其他模型的视图中使用这些方法,例如 VenueEventArtist

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def past_events
    self.events.select { |event| event.date < DateTime.now }
  end

  def future_events
    self.events.select { |event| event.date > DateTime.now }
  end
end

在视图中,它看起来像这样。

<%= "Upcoming events: " %>
  <% @user.future_events.each do |event| %>
    <% unless event.rsvp_status = "not_interested" %>
      <%= link_to event.title, event_path(event) %>
      <%= event.rsvp_status %>
    <% end %>
  <% end %>

here error I get: undefined method 'status=' for #<Rsvp::ActiveRecord_AssociationRelation:0x007fabb403b8f0>. it works if you do it directly like Rsvp.find(:id).status

奇数。 status= 表示您正在尝试为状态设置一个值...但如果您只是想查看状态则不应如此...

还有啊哈! Rsvp::ActiveRecord_AssociationRelation 表示您有一组 RSVP,而不是一个。您可能想要做的是在 where 的末尾添加一个 .first - 以确保您只有一个实际的 rsvp,而不是一整套(只有一个)在集合中)。

所以这意味着代码看起来有点像这样:

class User
  def rsvp_for_event(event)
    rsvps.where(:event_id => event.id).first
  end
end

并在您的模板中:

<% @user.future_events.each do |event| %>
  <% rsvp_status = @user.rsvp_for_event(event).status %>
  <% unless rsvp_status = "not_interested" %>
    <%= link_to event.title, event_path(event) %>
    <%= rsvp_status %>
  <% end %>
<% end %>

或不同的东西,但给出相同的最终结果:)

考虑一下,rsvp-scope 可能更漂亮

class Event
  scope :for_event, ->(event) { where(:event_id => event.id) }
end

并在您的模板中:

<% @user.future_events.each do |event| %>
  <% rsvp_status = @user.rsvp_for_event(event).status %>
  <% unless rsvp_status = "not_interested" %>
    <%= link_to event.title, event_path(event) %>
    <%= rsvp_status %>
  <% end %>
<% end %>