On 10 March 2016 at 15:05, John Sanderbeck <li...@ruby-forum.com> wrote:
> Colin Law wrote in post #1182080:
>> On 9 March 2016 at 23:19, John Sanderbeck <li...@ruby-forum.com> wrote:
>> attendance_count is not an attribute of organization, it is an
>> attribute of attendee so would need something like
>> Training.organizations.first.attendees.first.attendance_count
>> An organization has many attendees so for each organization there are
>> many values of attendance_count.  Which makes me realise that the
>> table example you posted does not make sense, as each organization
>> must have multiple rows.  If that is not the case then I do not
>> understand your associations.
>
> I think I have an idea on how I need to do this...
>
> If I add a scope to Organization that is like the following, would this
> work?
>
> scope :attendance, lambda {|trainingid|
> joins(:attendees).where("training_id = ?", trainingid).attendance_count
>
> Would this make sense?
>
> or would this be better in a method like
>
> def self.attendance(trainingid)
>   joins(:attendees).where("training_id = ?",trainingid).attendance_count
> end
>
> I just tried it both ways though and I get an undefined method
> attendance for the scope and an unknown method joins for the method so
> maybe my syntax is incorrect...

It is very unusual to need joins.  Assuming you are trying to get the
attendance count for a particular organization at a particular
training then you want something like
self.attendees.where(training_id: @training.id).first.attendance_count
or the equivalent in a scope.

You need the .first as the result of where will be (effectively) an
array even if there is only one.  Don't forget to allow for the
situation where there are no matching attendees (if that can happen)
in which case the array will be empty so the call to first will return
nil and the attempt to reference attendance count will fail.  One way
to get over that is to use 'try'.

Colin

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLvRCg%2B_ZKBL91d3SrWu3yhM1SEeV-uoVthtm-_hUXMWZA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to