简体   繁体   中英

Rails include model associations

is there a way to load model association without eager loading? im trying to push an object to the browser with model associations included.

push_to_user pushes the @todo object to the browser. a javascript listener will read the data and print it out.

The issue im having is that @todo doesn't include its model association (eg "categories"). how can i include that?

@todo = Todo.find(1)
puts @todo.item.categories  # eager load categories. works

# push object to pusher
Pusher.push_to_user(@todo, user)

# custom pusher method
def self.push_to_user(todo, user)
    Pusher['private-1'].trigger('activity', {:todo => todo, :user => user})
end

# Browser
console.log(todo) # categories are missing

thanks pete

I think the better is add a new key with this categories :

def self.push_to_user(todo, user)
    Pusher['private-1'].trigger('activity', {:todo => todo, :categories => todo.categories, :user => user})
end

You can call a #serializable_hash method on your todo with an :include => categories

def self.push_to_user(todo, user)
    Pusher['private-1'].trigger('activity', {:todo => todo.serializable_hash(:include => :categories), :user => user})
end

I don't test this solution but can works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM