Hi I am new to rails and started with a simple app which has many ‘tasks’ and each one have a ‘tag’ attached with it. So the relationship is like – Many ‘tasks’ have one/same ‘tag’. How do I bring this up in my models. I tried it with ‘task’ has_one ‘tag’ and a ‘tag’ belongs_to a ‘task’ rule but it works only for the first ‘task’ with that tag and for the rest of the ‘tasks’ with the same ‘tag’ it won’t work. Please suggest me the way to do this properly. Thanks 🙂
class Task < ActiveRecord::Base
has_many :logs
has_one :tag , :foreign_key => "id"
end
class Tag < ActiveRecord::Base
belongs_to :task
end
It looks to me like you have the associations turned around – every newbie to Rails that I’ve ever seen has done this on their first project.
What you want is
Think about it this way – if you click on a tag, you would expect a list of all tasks that have that tag. So tags have many tasks, and each task belongs to one tag. This matches how you described your project. Has_one is intended for a one to one relationship, where each task would have its own, unique tag.