Jeremy W. wrote:
So, I have been out of the rails loop for a little bit, and I’m not sure
the best “rails way” to do this. I have two objects. ObjectA has_many
:object_bs, and ObjectB belongs_to :object_a
In my controller I am trying to do basic CRUD operations. In my view I
have all the attributes of both ObjectA and ObjectB. So saying that
ObjectA has a name and id, and ObjectB has a kind and id and
object_a_id.
Basically what I want to do is
@a = Object.new(params[:object_a]), but when I do that I get an
undefined method because there are fields for a different object. What I
was doing is making a new_thing method which takes the params and goes
through each one and pulls out the ObjectA attributes and uses those,
then @a.object_bs << ObjectB.new(other param stuff).
I know there is a better way, I just need help learning what the is.
Thanks in advance, sorry if it is confusing.
~Jeremy
Here’s my take. First of all, you needn’t send either of the object ids
as parameters, as these are automatically taken care of by ActiveRecord.
And the object_a_id attribute of your ObjectB model can be taken care of
by creating it using the association.
That leaves us with ObjectB’s :kind attribute. I’m not perfectly sure if
this would work, but you may as well give it a shot and let me know.
In your ObjectA controller:
def create
@object_a = ObjectA.create(params[object_a])
# … (Various respond_to’s)
end
And in your ObjectA class:
class ObjectA
# I think that this will allow you store a value in the
# :kind attribute for this object while it exists in memory
# after being created by the controller. I could be mistaken.
attr_accessor :kind
# Standard AR callback
after_create :create_object_b
def create_object_b
# Creating the object_b through the object_a will take
# care of the has_many/belongs_to relationship.
self.object_bs.create(:kind => self.kind)
end
end
Good luck.