Views to handle a one-to-many relation?

Hello,
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 all guests belonging to it. The problem is I can see these relations, but yet can’t add new guests to a room (The ones I see were associated via script/console).

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

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

Thanks a lot for your help.
Sincerely,
Andrés.

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 guest.name, :controller => 'guests', :action =>
'new', :room_id => @room.id %>

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

@guest = Guest.new(:room_id => 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.new(params[:guest])
if(@guest.save)
(etc.)

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 => guest.id, :room_id => @room.id
%>
<% end %>

Hope that helps,
Julian.

Learn Ruby on Rails! Check out the FREE VIDS (for a limited time)
VIDEO #4 parts a and b now available!
http://sensei.zenunit.com/

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