I have 2 models, Users and Tasks
They are associated as given below :
class User < ActiveRecord::Base
has_many :tasks, foreign_key: "assigned_to"
end
The schema of the tasks model is given below :
t.string "taskable_type", limit: 255
t.integer "taskable_id"
t.string "title", limit: 255
t.text "description"
t.integer "added_by"
t.integer "assigned_to"
t.datetime "due_date"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "completed_at"
t.datetime "deleted_at"
I would also like to associate the field added_by to the users table.
How would I go about this?
You can add a second association, you just need to give it a unique name, such as:
class User < ActiveRecord::Base
has_many :tasks, foreign_key: "assigned_to"
has_many :added_tasks, foreign_key: "added_by", class_name: "Task"
end
You have to add the option class_name: "Task"
in this case because the proper class name cannot be inferred from the association name "added_tasks" (it would look for a class named "AddedTask").
The documentation for has_many lists the options to guide you through this sort of thing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.