Table associations and models best practice

I need some help understanding the proper way to save (if possible)
using the new(). create() method. I need an example to try to
explain.

Say, I have a table called projects with id, name, and
status_id as attributes along with another table called statuses with
id, name

My Project model will contain a “belongs_to :status” and Status model
will contain a “has_many :projects”.

Status table can contain (“active”, “scheduled”, “inactive”) along
with their respective ids.

I’m trying to figure out the proper way for, say, creating a new
project model using new() or create() with an ‘active’ id.

I’m looking to understand the difference between these and whether I
should always prefer to use one over the other…

p = Project.new(:name => “blah”, :status_id =>
Status.find_by_name(“active”).id)

p = Project.new(:name => “blah”, :status_id =>
Status.find_by_name(“active”))

p = Project.new(:name => “blah”, :status =>
Status.find_by_name(“active”).id)

p = Project.new(:name => “blah”, :status =>
Status.find_by_name(“active”))

Another question, along the same lines should I be doing the
following?

p = Project.new(:name => “blah”, :status_id => Status.new(:name=>
“test”))

p.save should create the new Status right?

Any help would be greatly appreciated. Thanks.

ray wrote:

Status.find_by_name(“active”).id)

p = Project.new(:name => “blah”, :status_id =>
Status.find_by_name(“active”))

p = Project.new(:name => “blah”, :status =>
Status.find_by_name(“active”).id)

p = Project.new(:name => “blah”, :status =>
Status.find_by_name(“active”))

If you use the enumerations_mixin plugin you can write

p = Project.new(:name => “blah”, :status => :active)

Another question, along the same lines should I be doing the
following?

p = Project.new(:name => “blah”, :status_id => Status.new(:name=>
“test”))

p.save should create the new Status right?

To create the new status you’d have assign the new Status object
to the status attribute rather than status_id.


We develop, watch us RoR, in numbers too big to ignore.