Views to handle a one-to-many relation?

I have a one-to-many relation between rooms and guests. A room has_many
guests, and a guest belongs_to a single room.

I’ve got a basic view for this, where I can show a room with a list of
guests belonging to it. The problem is I can see these relations, but
can’t add new guests to a room (The ones I see were associated via

I want to show a room with all its guests and a link that lets me add
guests to it. This link should take me to a list of all “roomless”
where I should be able to choose some of these guests and add them to a

I don’t know how to do this. Can you help me out?

Thanks a lot for your help.

Hi Andres,

There are many ways to do this.

Essentially, if you’re in the rooms/show page, (say with room’s id is
4 for the purposes of this example).

The url is /rooms/show/4

Now, the room is being shown in the view, with all its guests

The guests need to be links such as this:

<%= link_to, :controller => ‘guests’, :action =>
‘new’, :room_id => %>

Now in the new action of the guests controller, you’d have:

@guest = => params[:room_id])

and in the form for your guest, you’d have a hidden field

<%= hidden_field ‘guest’, ‘room_id’ %>

so that your guests/create action can take up the room_id attribute
when it is has

@guest =[:guest])

That’s one way to do it :slight_smile:

If you want it with your roomless guests, then your new action should
actually have something like:

@guests = Guest.find(params[:guest_id])
@roomless_guests = Guest.find(:all, :conditions => “room_id IS NULL”)

So that you’re not creating them, and then the links will link to some
other action, which associates the id’s.

<% for guest in @guests %>
<%= link_to ‘associate’, :action =>
‘associate_guest_to_room’, :guest_id =>, :room_id =>
<% end %>

Hope that helps,

Learn Ruby on Rails! Check out the FREE VIDS (for a limited time)
VIDEO #4 parts a and b now available!

Thanks a lot for your help, Julian. It has been very useful for me :slight_smile:

On Sun, Jun 1, 2008 at 10:35 AM, Julian L.
[email protected]