开发者

Rails - retrieving data across 3 tables in has many through

开发者 https://www.devze.com 2023-02-17 05:32 出处:网络
I have a basic event management app in rails 3- users (model: user) can create events (model: event) as hosts (:event belongs_to user). Other users can attend the events (:user has_many :attending, :t

I have a basic event management app in rails 3 - users (model: user) can create events (model: event) as hosts (:event belongs_to user). Other users can attend the events (:user has_many :attending, :through => :attendances, :source => :event). All of these models and associations are working fine (a good start).

# the user model
class User < ActiveRecord::Base     
    has_many :events, :dependent => :destroy
    has_many :attendances, :foreign_key => "attendee_id", :dependent => :destroy
    has_many :attending, :through => :attendances, :source => :event
end

# the events which users create
class Event < ActiveRecord::Base    
    belongs_to :user
    has_many :attendances, :foreign_key => "event_id",:dependent => :destroy
    has_many :guests, :through => :attendances, :source =>:user
end

# the join model for attendances
class Attendance < ActiveRecord::Base    
    belongs_to :attendee, :class_name => "User"   #edit: addedin :class_name... after comment
    belongs_to :event, :class_name => "Event"
end

Now the problem: I have a 'manage events' page where the host should be able to see all the requested attendances to his events, and accept or decline their attendance. I can get the list of events which are hosted by the user (<%= render @user.events %>) but cant seem to work out how to bring back the list of all the users who have requested attendance at the hosts' events (to allow the host to accept or decline guests).

<html>
<% unless @user.events.empty? %>   #code on the manage events page
    <table class="events" summary="User Events">
        <%= render @user.events %>
    </table>
<% end %>
</html>

I'm sure the solution is simple, but 2 day开发者_高级运维s of playing around and im getting nowhere quickly.


In the partial in which you render the attendees for an event, you can do something like this:

<%= event.name %><br/>
<% event.attendances.each do |a| %>
   <%= a.attendee.name %><br />
<% end %>

Or in the same view, similarly you can write:

<%= @event.name %><br/>
<% @event.attendances.each do |a| %>
   <%= a.attendee.name %><br />
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号