Forum: Ruby on Rails One-to-Many Associations (newbie)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5590789d20e9a2112f34534e51a007c0?d=identicon&s=25 Mason Kessinger (Guest)
on 2006-12-30 20:16
I have two databases Tours and Bands such that:

- - begin code - -

  class Band < ActiveRecord::Base
    belongs_to :tours
  end

  class Tour < ActiveRecord::Base
    has_one :bands
  end

- - end code - -

In my admin_tours I have added a bit of code that gives me a drop down
menu with a selection of all bands in Bands:

- - begin code - -

  <p><label for="band_id">Band</label><br>
  <%= select("band", "band_id", Band.find_all.collect {|p| [ p.name,
p.id ] }) %>

- - end code - -

Of course you imagine that I am looking to have band_id save when i save
tours. I am having a difficult time figuring out what code works I
should put in my 'admin_tours_controller'. As I have scaffolded this out
so I am assuming I should be adding some sort of save code to 'update'
and 'create'.

I am willing to pay someone to walk me thru this (aim? tele?) or if you
have any quick (free) advice that would work too.

: )

thanks!

-----------------------
 Mason Kessinger
-----------------------
 http://www.poccuo.com
-----------------------
72f8ab180f81f9c544e2b58da399c0be?d=identicon&s=25 Elad Meidar (eizesus)
on 2006-12-30 23:11
(Received via mailing list)
> - - begin code - -
>
>   class Band < ActiveRecord::Base
>     belongs_to :tours
>   end
>
>   class Tour < ActiveRecord::Base
>     has_one :bands
>   end
>

First, this should be has_one :band, not :bands
> - - begin code - -
>
>   <p><label for="band_id">Band</label><br>
>   <%= select("band", "band_id", Band.find_all.collect {|p| [ p.name,
> p.id ] }) %>
>

I don't know how did you built your DB schema, but it should be
something like this

----

table bands:
id
name
tour_id
(other columns)

table tours:
id
location
(other columns)

----

in this case, when using belongs_to - has_one, the child element (aka
the one who belongs to other) need to have a column indicating it's
association id (in my ex. it's tour_id) that's how you will get your
relation.

as for the select it's should be <%= select_tag "tour", "band_id",
Band.find(:all).collect {|e| [e.name, e.id]} %>

if i missed your point, i'll be happy to help you for free of course if
you refer to my by mail (elad@creopolis.com) or by MSN
(eizesus@hotmail.com).

hope this helps
This topic is locked and can not be replied to.