Polymorphic reference deeper?

I have made myself a small activity model like this =>

== Schema Information

Schema version: 20110519174324

Table name: activities

id :integer not null, primary key

account_id :integer

action :string(255)

item_id :integer

item_type :string(255)

created_at :datetime

updated_at :datetime

belongs_to :account
belongs_to :item, :polymorphic => true

from this i can get a nice timeline/actions/userfeed or what we want
to call it from =>

def self.get_items(account)
item_list = []
items = where(:account_id => account.id).order(“created_at
DESC”).limit(30)
items.each do |i|
item_list << i.item_type.constantize.find(i.item_id)
end
item_list
end

it works like a charm for objects not refering to others - like if a
user uploads a new image i can
get the image nice and tidy. But for comments => then i want to get
the original post info, can i get
that in get_items directly ? Someone got tips for me ?

/Niklas

On May 20, 11:48am, Niklas N. [email protected] wrote:

item_id :integer

def self.get_items(account)
item_list = []
items = where(:account_id => account.id).order(“created_at
DESC”).limit(30)
items.each do |i|
item_list << i.item_type.constantize.find(i.item_id)

Quick note here - this can be more effectively replaced by:

item_list << i.item

since that’s the whole point of the :polymorphic => true
declaration…

it works like a charm for objects not refering to others - like if a
user uploads a new image i can
get the image nice and tidy. But for comments => then i want to get
the original post info, can i get
that in get_items directly ? Someone got tips for me ?

I suspect you’ll likely be doing that farther up in the code, where
the results of get_items are used. For instance, one might do
something like this:

<%= Activity.get_items(some_account).do |item| %>
<%= render :partial => “#{item.class.name.underscore}”, :locals =>
{ :item => item } %>
<% end -%>

then the individual item partials can deal with calling more methods
on the object.

–Matt J.

Thanks Matt,

Now i just have to figure out how to do the “calling more methods on
the object”.
I havent seen or used “#{item.class.name.underscore}” so i guess the
key are in that - hopefully i dig into this.

/Niklas.

Got it working, you are my hero!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs