开发者

DataMapper => One-to-Many filter

class Task
  include DataMapper::Resource
  has 1, :list, :through => Resource
end

class List
  include DataMapper::Resource
  has n, :tasks, :through => Resource
end

A list has many tasks. Suppose I h开发者_JAVA百科ave a task with id = 1.

How do I do to find the list that has this task?

I tried : List.first(:tasks => task) but it always returns nil.

Thank you.


what about Task.first(:id => 1).list? By the way, you should really change the definitions of your models. I recommend you to read the datamapper documentation thoroughly.

class Task
  include DataMapper::Resource

  belongs_to :list
end

class List
  include DataMapper::Resource

  has n, :tasks
end

Doesn't that look much nicer? Oh and I hope you defined keys. These are important for well working associations. And if id is the key for Task your query would simplify to Task.get(1).list.


You can used a nested condition like this:

List.first(:tasks => { :id => task.id })

but given a task it would be simpler to use task.list


Why do you have has 1 through resource? I would do Task.belongs_to :list and then List.has n, :tasks so you could write:

List.first :"tasks.id" => task.id

Although if you already got the task then it's simpler to just write task.list :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜