#003_通过表间关联来查找

Rails不要求在迁移任务中建立外键约束,在迁移任务中创建project_id字段后在Project和Task模型中加上相应的声明。
# project.rb
has_many :tasks

# task.rb
belongs_to :project

# projects_controller.rb
def show
  @project = Project.find(params[:id])
  @tasks = Task.find(:all, :conditions => [ 'project_id = ? AND complete = ?', @project.id, false ])
end

于是,projects_controller.rb中show action的第2行代码可以改写一下
@tasks = @project.tasks.find_all_by_complete(false)

你可能感兴趣的:(Ruby,Rails)