Forum: Ruby on Rails How to add virtual fields in model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
59bea58f406ca9f19f7820c79d61bfc9?d=identicon&s=25 Superbiji (Guest)
on 2006-01-13 13:12
I want to add virtual fields in a model.

table: field1 field2
I want to add field3 which is field1*2 + field2


I know tihs can be achieved in View, but I want it in model.
Then I will pass this model to PagerRenderer to paginate.

How to achieve this?

thanks
C8a634a01a2c4508360874bff7fb1a7f?d=identicon&s=25 Kevin Olbrich (olbrich)
on 2006-01-13 13:37
Superbiji wrote:
> I want to add virtual fields in a model.
>
> table: field1 field2
> I want to add field3 which is field1*2 + field2
>
>
> I know tihs can be achieved in View, but I want it in model.
> Then I will pass this model to PagerRenderer to paginate.
>
> How to achieve this?
>
> thanks

In your model...

def field3
 field1 + field2
end
E19aad1bd12334587247f7575e6480c1?d=identicon&s=25 Peter Sumskas (Guest)
on 2006-01-13 13:38
(Received via mailing list)
Something like the following should work just fine:

class YourModel
  ...
  def field3
    field1 * 2 + field2
  end
end

As for rendering the list. It should paginate fine - but you might not
be
able to use the standard way of determining which columns will be
rendered
(I don't think it will pick up your "virtual field"). Someone with more
experience could chime in here.

Cheers,
Pete.
59bea58f406ca9f19f7820c79d61bfc9?d=identicon&s=25 Superbiji (Guest)
on 2006-01-13 13:41
Kevin Olbrich wrote:
> def field3
>  field1 + field2
> end

@pages, @items = ctx.paginate tablename, opt

I've did that, but my field3 does not shown in @items
59bea58f406ca9f19f7820c79d61bfc9?d=identicon&s=25 Superbiji (Guest)
on 2006-01-13 13:47
Peter Sumskas wrote:
> As for rendering the list. It should paginate fine - but you might not
> be
> able to use the standard way of determining which columns will be
> rendered

My PagerRenderer is dumb renderer, which I will use for all my model. It
iterates model's columns using  @items[0].class.content_columns
This topic is locked and can not be replied to.