Forum: Ruby on Rails Basic Many-to-One association

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.
25bbc96d9c53647354cb724e744b2222?d=identicon&s=25 Greg Freemyer (Guest)
on 2006-01-27 01:21
(Received via mailing list)
Sari,

I got the list display working without doing an explicit find.

It took a bit of a conceptual convulution to get it to work.  I was
thinking of it has Many Cases have One status.

There is no support for Many-to-One so I was a bit stumped.

Then I realized you just have to turn around your thinking to say One
Status has Many Cases.  Thus it is a One-to-Many relationship.  That
is descriped on page 234 of the book.

Below is a list of what I did in my code.

=========
1) I changed the name of the field "status_id" in the cases table to
"case_status_id"

Then fixed the error this caused in case_controller.rb by simply
changing the name of the status_id field reference.

I did the same name change in app/view/case/list.rhtml, but then I
modified that line later anyway.

I'm sure I missed a bunch I was just trying to get a proof of concept
working.

2) I added a "belongs_to :case_status" line to the app/models/case.rb
file.

Thus rails now thinks that status is the master table and case is a
detail table.  Sort of strange but I think that is actually correct.

(ie. Each Status (One) has multiple Cases (Many) as detail records!!!)

We probably should add "has_many :cases" to the case_status model as
well.  I did not need that for the below to work, but it is part of
what is describe on page 234.

3) I edited the app/view/case/list.rhtml file to replace

     <%=h CaseStatus.find(a_case.status_id).status %>
with
     <%=h a_case.case_status.status %>

Now that this is done, you should be able to use
"a_case.case_status.active" as well in the controller.

Hope that helps
Greg
--
Greg Freemyer
The Norcross Group
Forensics for the 21st Century
25bbc96d9c53647354cb724e744b2222?d=identicon&s=25 Greg Freemyer (Guest)
on 2006-01-27 01:24
(Received via mailing list)
Apologies, I did not mean to send the below to the list.

Please ignore my previous post.

I was composing a question when I realized the answer.  I forgot to
take the list out of the to line.

Greg

On 1/26/06, Greg Freemyer <greg.freemyer@gmail.com> wrote:
> Status has Many Cases.  Thus it is a One-to-Many relationship.  That
>
> (ie. Each Status (One) has multiple Cases (Many) as detail records!!!)
>
> Now that this is done, you should be able to use
> "a_case.case_status.active" as well in the controller.
>
> Hope that helps
> Greg
> --
> Greg Freemyer
> The Norcross Group
> Forensics for the 21st Century
>


--
Greg Freemyer
The Norcross Group
Forensics for the 21st Century
This topic is locked and can not be replied to.