has_many and belongs_to, how to print creator's name
I have a user table(id, username, ...), and I have a task table, this implies the tasks 开发者_运维百科informations: task name, the creator's id and the task solver's id.
This is my dbase logic:
class User < ActiveRecord::Base
has_many :tasks, :foreign_key=>"creator_id"
has_many :tasks, :foreign_key=>"solver_id"
end
class Task < ActiveRecord::Base
belongs_to :user
end
Is this right? In Task list I want to print the creators name. How can I do that?
In your Task model you want:
belongs_to :creator, :foreign_key => "creator_id", :class_name => "User"
belongs_to :solver, :foreign_key => "solver_id", :class_name => "User"
and in your User model:
has_many :created_tasks, :foreign_key=>"creator_id", :class_name => "Task"
has_many :solved_tasks, :foreign_key=>"solver_id", :class_name => "Task"
So now you can do something like:
@user.created_tasks
@user.solved_tasks
and @task.creator
and @task.solver
精彩评论