On Wednesday, June 20, 2018 at 1:40:34 PM UTC-7, craig buchanan wrote:
>
> I have a contacts table with fields that include `first_name` and
> `last_name`. I have a corresponding model `Contact` (inherits
> Sequel:Model) that has a instance method named `full_name`:
>
> def full_name
> "#{first_name} #{last_name}"
> end
>
> This method returns a value when looking at a single Contact instance:
>
> irb> Contact.first.full_name
> => "John Doe"
>
>
> However, this syntax returns an error:
>
> irb> Contact.where(Sequel.ilike(:last_name,"D%")).select(:first_name,:
> last_name,:full_name).all
> Sequel::DatabaseError (SQLite3::SQLException: no such column: full_name)
>
> I'm assuming this is because the `.all` method returns a dataset, not a
> collection of instances.
>
> I'm aware of the `concat` function:
>
> :concat.sql_function(:a, :b) # SQL: concat(a, b)
>
> What's the correct way to define a `full_name` field in my class such that
> it can be used in SELECTs and WHEREs?
>
def self.full_name_expr
Sequel.join([:first_name, :last_name], ' ')
end
Contact.where(Sequel.ilike(:last_name,"D%")).select(:first_name,:last_name,
Contact.full_name_expr.as(:full_name)).all
Sequel does not offer a simple way to make :full_name usable as a string
concatenation expression. It is possible to do so by overriding some
methods, but not advisable. For one, when used in SELECT, you would want
to alias the expression, but when used in WHERE you would not as aliases
are not allowed in the WHERE clause.
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 https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.