Question

I have just implemented a feature on my site which allows users to re-order the nav and then the custom positioning is saved to the database.

This part is fine but before I had created a model which inherited from ActiveRecord::Base, e.g.

class MenuItem < ActiveRecord::Base

but to avoid creating a new table for every type of preference I've refactored it to inherit from UserPreference:

class MenuItem < UserPreference

class UserPreference < ActiveRecord::Base

so in my ApplicationController I am doing the following:

before_filter :get_user_preferences

def get_user_preferences
  @user_preferences = UserPreference.find_all_by_user_id(@person.id)
  @menu_items = @user_preferences.select{|x| x.type == MenuItem}
end

Then at the moment in my partial which handles the nav I have the following:

<%= debug @menu_items %>

An example object is

- !ruby/object:MenuItem 
  attributes: 
    key: dashboard
    created_at: 2014-03-13 12:43:43 +00:00
    updated_at: 2014-03-13 12:43:43 +00:00
    user_id: 940
    id: 1
    value: "1"
    type: MenuItem
    attributes_cache: {}

So, the question is, is there a quick way I can select the object based on it's key attribute?

What I want to achieve is:

<li data-sort="<%= !value_attribute_from_object.blank? ? value_attribute_from_object : '1' %>" data-id="key_attribute_from_object">

so the resulting html would be

<li data-sort="1" data-id="dashboard">

Then I do the same for all my other sections.

The ways I've thought about doing it are simply setting individual variables for the key and value for every object but I'd rather do it a smarter way if possible so that I don't need to remember and update this part of the code if a new section is added (or even if a current section is removed).

Is there such a way or do I just need to bite the bullet?

Was it helpful?

Solution

Not sure if this is what you mean,

dashboard_value = @menu_items.select{|item| item.key == 'dashboard'}.map(&:value)

This will give you the value of the object with the key 'dashboard'

[EDIT]

If you have an array of values

 value_array = ['dashboard', 'another_item']
 kv_pairs = {}
 value_array.each do |val|
   kv_pairs[val] = @menu_items.select{|item| item.key == val}.map(&:value)
 end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top