Problem in has_and_belongs_to_many data retrieval

Hi All,

I’m new in RoR, I have a problem in retrieving data in
has_and_belongs_to_many relationship.

I have created 3 tables, Tag, Entry and Entries_Tags .
There are join in has_and_belongs_to_many

I can successfully create new record by this relationship. But I cannot
retrieve the data.

I want to do a task to select all Entries with condition "name = ‘g’ in
Tag table.

I use this code to select all the record with name = ‘g’
@resulttag = Tag.find(:all, :conditions => “name = ‘g’”)

Then I want to select all related Entries record, by this code
@r = @resulttag.entries

But it is not work, @r still storing the same data with @resulttag (The
array storing Tag records, not Entry records)

Can anyone can help or provide a solution to do such task ???

Thanks a lot,
Stanley

=================CODE===========================================
def showresult

@resulttag = Tag.find(:all, :conditions => "name = 'g'")
logger.info("Size = #{@resulttag.size}")
@r = @resulttag.entries
logger.info("RSize = #{@r.size}")

@resulttag.entries.each do |en|
  logger.info("RES = #{en.id}")

end

==================LOG===========================================
Size = 8
RSize = 8
e[4;35;1mTag Columns (0.011401)e[0m e[0mSHOW FIELDS FROM tagse[0m
RES = 10
RES = 11
RES = 12
RES = 13
RES = 14
RES = 16
RES = 17
RES = 18

On 19 Nov 2007, at 07:31, Stanley Wong wrote:

It’s not working because @resulttag is an array of tags, not a single
tag
@resulttag.entries.collect(&:entries) will give you an array
containing an array for each tag, or if you want an array with all
entries,
@resulttag.entries.collect(&:entries).flatten will do the job

You could also approach it the other way round:

Entry.find_by_sql <<_SQL
SELECT * from entries
INNER JOIN entries_tags on entries.id = entry_id
INNER JOIN tags on tags.id = tag_id
where name = ‘g’
_SQL

Fred

Hi Fred,

Thx, it’s work

Stanley

Frederick C. wrote:

On 19 Nov 2007, at 07:31, Stanley Wong wrote:

It’s not working because @resulttag is an array of tags, not a single
tag
@resulttag.entries.collect(&:entries) will give you an array
containing an array for each tag, or if you want an array with all
entries,
@resulttag.entries.collect(&:entries).flatten will do the job

You could also approach it the other way round:

Entry.find_by_sql <<_SQL
SELECT * from entries
INNER JOIN entries_tags on entries.id = entry_id
INNER JOIN tags on tags.id = tag_id
where name = ‘g’
_SQL

Fred