Reputation: 2443
I have a model called Topic and another called Product.
Here's how the Topic model looks,
class Topic < ActiveRecord::Base
belongs_to :product
end
Topic has columns "title" and "body".
And here's Product,
class Product < ActiveRecord::Base
has_many :topics
end
Product has columns "name" and "desc". Name is unique.
When I create a new Topic, I want the title of Topic to be stored in Name of Product, only if Name doesn't exist yet. If it does, it should not make any change.
But how do I do this?
UPDATE:
User comes to /topics page, enters Title and Body.
What the Topics_controller should do, 1. Read the Title that has been given by the user. 2. Check if that Title already exists in the Products. 3. If it doesn't add it. 4. If it does, don't do anything.
I don't understand how these two models are linked together and how I can access records from the model.
Upvotes: 0
Views: 115
Reputation: 203
Your requirements are a bit unclear here. Can you specify what your end goal is, from a Behaviour point of view?
If i understand correctly though, why not just overwrite the title method for Topic. This way you are not duplicating data in the DB.
within your Topic class:
class Topic < ActiveRecord::Base
def title
read_attribute(:title) || product.name # will get title of @topic if not nil, else product name
end
end
Upvotes: 0
Reputation: 8498
You can achieve this by using one of the callbacks, which ActiveRecord provides.
I'm not sure if I understand your requirements perfectly, so maybe you need to alter the following example:
class Topic < ActiveRecord::Base
belongs_to :product
before_save :add_product_name
private
def add_product_name
self.product.name ||= self.title if Product.find_by(name: self.title).nil?
end
end
Upvotes: 2
Reputation: 1038
You can write a callback like before_create :add_topic_name
Where that method will find product name of topic and assign it to the title of product.
Upvotes: 0