hi everyone,
I’ve pasted some code over there http://pastie.org/230343 .
what I find strange is that the extra field in the join table called
“quantity” doesn’t shows up in the Drug resultset, even if I added an
attr_accessor for good measure.
anybody knows why? I’m on edge rails.
thanks.
On Jul 9, 2:37 am, Claudio P. [email protected] wrote:
hi everyone,
I’ve pasted some code over therehttp://pastie.org/230343.
what I find strange is that the extra field in the join table called
“quantity” doesn’t shows up in the Drug resultset, even if I added an
attr_accessor for good measure.
The attr_accessor would actually squash the attribute if it were
there.
It’s normal not to get the join table attributes - that’s just the way
rails does things. Your workaround with the explicit select clause
should work, I expect that you are being fooled by ActiveRecord’s
display of your instance of Drug, which only displays attributes from
the drugs.table. Document.find(2).drugs.first.quantity should work
(but get rid of the attr_accessor first).
Fred
Frederick C. wrote:
On Jul 9, 2:37�am, Claudio P. [email protected] wrote:
hi everyone,
I’ve pasted some code over therehttp://pastie.org/230343.
what I find strange is that the extra field in the join table called
“quantity” doesn’t shows up in the Drug resultset, even if I added an
attr_accessor for good measure.
The attr_accessor would actually squash the attribute if it were
there.
It’s normal not to get the join table attributes - that’s just the way
rails does things. Your workaround with the explicit select clause
should work, I expect that you are being fooled by ActiveRecord’s
display of your instance of Drug, which only displays attributes from
the drugs.table. Document.find(2).drugs.first.quantity should work
(but get rid of the attr_accessor first).
Fred
One way to guarantee the method exists,
and allow you to cast it to an integer would be;
class Drug < ActiveRecord::Base
def quantity
self[:quantity].to_i
end
end
But I don’t like it,
because “quantity” isn’t actually a value of of the Drug,
it’s a value of the join.
clearly;
drug = document.drugs.first
drug.quantity != drug.reload.quantity (which will always be 0)
I’d prefer the following syntax;
drug = documents.drugs.first
quantity = documents.quantity_of_drug(drug)
class Document < ActiveRecord::Base
def quantity_of_drug(drug)
if join = join_for_drug(drug)
return join.quantity
else
return 0
end
end
private
def join_for_drug(drug)
self.document_drugs.detect {|dd| dd.drug == drug}
end
end
however you’d need to ensure you loaded drugs through document_drugs,
rather than by a direct join
(not quite sure what rails does about this at the moment)
thanks for the suggestions, I’m going to do a bit of work on that as
advertised.