Rails between many associations

Hi, I am new to rails and started with a simple application that has many “tasks” and each of them has a “tag” attached to it. Thus, the relationship is similar to: “Many“ tasks ”have the same“ tag. ”How to do this in my models. I tried it with the tag 'task' has_one 'tag' and 'tag' belongs to the rule 'task' but it only works for the first "task" with this tag, and for the rest of the "tasks" with the same "tag", this will not work. Please suggest me a way to do it right. Thanks :)

class Task < ActiveRecord::Base has_many :logs has_one :tag , :foreign_key => "id" end class Tag < ActiveRecord::Base belongs_to :task end 
+4
source share
3 answers

It seems to me that you have formed associations - every Rails newbie I've ever seen did this in his first project.

Do you want to

 class Task < ActiveRecord::Base has_many :logs belongs_to :tag end class Tag < ActiveRecord::Base has_many :tasks end 

Think of it this way: if you click on a tag, you expect a list of all the tasks that have this tag. Therefore, tags have many tasks, and each task belongs to one tag. This is consistent with how you described your project. Has_one is for a one-to-one relationship, where each task will have its own unique tag.

+9
source

Perhaps your problem is that using the foreign key "id" means that you are using the "ids" column as a keyword, which is counterintuitive. In this case, the task id 1 believes that it will be associated with the id 1 tag.

If you installed your migrations using the RAILs conventions, I would suggest that you have a column in the tag table that writes task_id. In this case, I think you just need these associations:

  class Task < ActiveRecord::Base has_many :logs has_one :tag end class Tag < ActiveRecord::Base belongs_to :task end 

Again, this assumes that you have an attribute for tags called "task_id". If you saved it in a non-traditional way, for example, "custom_name_task_id", it will change to

  class Task < ActiveRecord::Base has_many :logs has_one :tag, :foreign_key => "custom_name_task_id" end class Tag < ActiveRecord::Base belongs_to :task end 
+2
source

If you understand correctly, you want the task to have only one tag, but this tag can belong to several tasks, the association is the opposite. You need belongs_to :tag in the Task and has_many :tasks in the tag.

But, I think, you will probably eventually want some tags for one task, and I would have thought from the very beginning to make an MM relationship, for example:

 class Task < ActiveRecord::Base has_many :tagged_tasks has_many :tags, through: :tagged_tasks end class Tag < ActiveRecord::Base has_many :tagged_tasks has_many :tasks, through: :tagged_tasks end class TaggedTask < ActiveRecord::Base belongs_to :task belongs_to :tag end 

This allows you to have multiple tags for tasks, but you probably should just use act_as_taggable_on , which does all of this for you.

+1
source

Source: https://habr.com/ru/post/1388876/


All Articles