Reputation: 284
So I have two models, call them Animal
and AnimalComment
. They look like this:
class AnimalComment < ActiveRecord::Base
attr_accessible :comment, :num
end
class Animal < ActiveRecord::Base
attr_ accessible :species, :comment
end
I when ever I create a comment in Animal
I would like it to add that comment into the :comment
field of my AnimalComment
Model.
My vision of how this works is I type in a comment in my animals/new
webpage, and when I click Submit
The comment get's added as a field inside my AnimalComment
webpage and is displayed there.
Hope this makes sense. Any ideas?
Upvotes: 1
Views: 662
Reputation: 19308
I am not sure it makes sense to have the same data stored in two places. Perhaps the models should be related (i.e. an Animal
has_many
Comments
).
In any case, your requirement can be satisfied with a callback.
class Animal < ActiveRecord::Base
attr_accessible :species, :comment
after_save :create_animal_comment
def create_animal_comment
AnimalComment.create(comment: self.comment)
end
end
The after_save
method tells Rails to run the Animal#create_animal_comment
method every time an Animal
record is created. self.comment
refers to the comment in the Animal
model.
Upvotes: 4
Reputation: 3919
First, create associations. Then save the comment only in the AnimalComment table. Use delegate
in the Animal model to access it, or get it through the association.
Upvotes: 1