Listing parents from child conditon


#1

Hi,

How can I grab all parents in a table, depending on a condition in the
children table ?

Fx.
def list
@projects = Project.find(:all)
end

will find all projects in my table. Now let’s say I want show a similar
list, for all open projects… I define an open project, as all lines
(Line has belongs_to :Project) that do not yet have a closed_at
timestamp set.

So basically, I want all projects, where project.line.closed_at is NULL.

How would I do that ?

/mich


#2

Read the documentation for find(). Look at the syntax for the
:conditions parameter.

mich wrote:

Hi,

How can I grab all parents in a table, depending on a condition in the
children table ?

Fx.
def list
@projects = Project.find(:all)
end

will find all projects in my table. Now let’s say I want show a similar
list, for all open projects… I define an open project, as all lines
(Line has belongs_to :Project) that do not yet have a closed_at
timestamp set.

So basically, I want all projects, where project.line.closed_at is NULL.

How would I do that ?

/mich


#3

Steve K. wrote:

Oh, sorry… I didn’t read carefully enough! Sorry I came off trollish.
:wink:

No worries.

Try something like

@projects = Project.find(:all, :conditions => “lines.closed_at IS NULL”,
:include => :lines)

Cheers.


#4

Oh, sorry… I didn’t read carefully enough! Sorry I came off trollish.
:wink:

Try something like

@projects = Project.find(:all, :conditions => “lines.closed_at IS NULL”,
:include => :lines)

mich wrote:

Hi,

How can I grab all parents in a table, depending on a condition in the
children table ?

Fx.
def list
@projects = Project.find(:all)
end

will find all projects in my table. Now let’s say I want show a similar
list, for all open projects… I define an open project, as all lines
(Line has belongs_to :Project) that do not yet have a closed_at
timestamp set.

So basically, I want all projects, where project.line.closed_at is NULL.

How would I do that ?

/mich


#5

I’m not 100% sure, but you might try this:

Project.find(:all, :include ‘Line’, :conditions => [“Line.closed_at is
NULL”])

HTH


#6

If that doesn’t work you can use find by sql

Project.find_by_sql(“select DISTINCT project.* from project, line
where
line.closed is null and project.id = line.project_id”)

There may be a better ‘rails-y’ way, but i’m not sure

The agile programming with rails book has a very extensive discussion of
find. It’s very worthwhile to have.