On Wednesday, April 8, 2015 at 11:09:28 AM UTC-7, Andrew Burleson wrote:
>
> Suppose I have a one to many relation like so...
>
> class Bar < Sequel::Model
> one_to_many :foos
> end
>
>
> class Foo < Sequel::Model
> many_to_one :bar
> end
>
>
> ...and I'd like to get a "previous foo" method that can be called on an
> instance. I can do it like this:
>
> # inside class Foo
> def previous_foo
> this = self
> bar.foos.order(:created_at).first{created_at < this.created_at}
> end
>
>
> This all works fine fine, but setting `this = self` to distinguish the
> instance value from the database column feels a little odd. Is there a
> better recommended way to do this in Sequel?
>
In terms of avoiding the this = self, just provide a block argument for the
virtual row:
bar.foos_dataset.order(:created_at).first{|o| o.created_at < created_at}
When you provide an argument, the virtual row code doesn't instance_exec
the block.
I think a faster approach would be to do:
model.order(:created_at).first(:bar_id=>bar_id){|o| o.created_at <
created_at}
This avoids the extra query to load bar.
Also, I'm guessing you want reverse(:created_at) instead of
order(:created_at).
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.