On Mar 3, 9:51 am, Jeremy Evans <[email protected]> wrote:
> On Mar 2, 8:38 pm, pachl <[email protected]> wrote:
>
> > Is it possible to select a column alias and have it automatically
> > assigned to the corresponding model object attribute. I'm assuming
> > this is a form of virtual attributes.
>
> > I posted an example snippet of an Erubis view and Sequel 
> > model:https://gist.github.com/852330.
>
> > The :body_preview attribute always returns nil.
>
> > My select statement does include include a literal, but I even dumbed
> > it down with no luck. For example:
> >   1) :body.as(:body_preview)
> >   2) :body___body_preview
>
> > Maybe I'm misunderstand how Sequel works here. Any help will be much
> > appreciated.
>
> You can't use attr_accessor to create virtual attributes.
> attr_accessor stores data in instance variables, while all of Sequel's
> column data is stored in the values hash.  I would recommend doing it
> like this instead:https://gist.github.com/853073
>
> If you really want to create a method, you want to call the
> def_column_accessor method instead of the attr_accessor method.
>
> Jeremy

Thanks for clearing that up Jeremy. I've read through all of the
Sequel docs, but I wasn't aware of the values hash. I'll have to re-
read.

I figured there would be class method called `virtual_accessor' or
something. Well I didn't use `def_column_accessor'. Instead, I defined
an instance method that simply returns the proper object from the
values hash because it is readonly:

    def body_preview
      self[:body_preview]
    end

Once you helped me fix my virtual column issue, I uncovered another
problem, as you might have guessed. My select in the code snippet was
a mess:

    .select(:headline, 'substring(body from "^.*?</
p>")'.as(:body_preview))

After looking at the Sequel docs, it looks like I need Virtual Row
Blocks. I just could not get this thing to work properly, so I
defaulted literal SQL:

    .select(:headline, "substring(body from '^.*?</p>') AS
body_snippet".lit)

The ORM version was getting very cumbersome and confusing compared to
the raw SQL. Thank god for #lit in my case.

Thanks much Jeremy!

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en.

Reply via email to