Question

I have a Lines model which uses the ancestry gem.

A line can have children and parent lines.

I have a Miniatures model.

Lines has_many Miniatures through the Minilines table.

In my Lines views I can show all associated miniatures for that Line. That works.

What I'd like to be able to do is show all associated miniatures for that line AND it's children.

It needs to use distinct true or uniq in case a miniature is associated with a Line and one of it's subtree Lines.

With some talking to someone working on the ancestry gem I put the following in my view:

 <% Miniature.select('distinct *').joins(:lines).where(@line.subtree_conditions).each do |miniature| %>
    <%= link_to miniature.name, miniature %><br />
 <% end %>

He didn't think my problem was a problem with the gem, rather a rails problem.

What that code does is make a link to a miniature (correct) but with the name and id of the line that that miniature belong to, rather than the name and id of the miniature. After a lot of fiddling around I am so close to getting it to work.

I changed the code to this

<% Line.select('distinct *').joins(:miniatures).where(@line.subtree_conditions).each do |miniature| %>
    <%= link_to miniature.name, miniature %><br />
<% end %>

It now outputs the correct looking thing. The name of the miniature. It also has the correct miniature_id but for is linking, bewilderingly, to a line path rather than a miniature path. For instance it shows the name of miniature number 3 but links to localhost:3000/lines/3.

I'll keep fiddling with it but if anyone can see the exact problem I'll be over the moon.

Cheers.

Était-ce utile?

La solution

In your second code block, the records being returned are NOT Miniature objects, they are Line objects - that's the class you queried, that's the class you'll get. :)

In the first case, I'd guess that Line has id and name columns which are shadowing the ones coming from Miniature. Try this instead: Miniature.uniq.joins(:lines).where(@line.subtree_conditions) which will give you a SELECT that explicitly targets only the fields from the miniatures table.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top