The Problem is solved, see below for solution

The original problem

I have a very basic ruby question relating to the use of Active Records.

Here I have a user

  class User < ActiveRecord::Base
    has_many :user_prefs
    def save_pref(name,value)
      self.user_prefs << UserPref.create(name,value)
    end
  end

and prefs

  class UserPref < ActiveRecord::Base
    belongs_to :user
  end

in my app

how do I then add a new preference to the user?

  aUser = User.new
  aUser.save_pref("test","test value")
  aUser.save!

saves the user but not with the pref data.

  1. what am I doing wrong?

  2. how would I write a get_pref(name) method?

  3. what is the best way of ensuring that there is only ever one pref named "test"?

      aUser.save_pref("test","test value")
    aUser.save_pref("test","test value 2")
    assert_equals aUser.get_pref("test") , "test value 2"
    

ie is there an automajic way I can ensure that the UserPrefs in user_prefs have unique names?

In java I'd do all this sort of things with HashTables or Sets and let JDO or Hybernate deal with the database stuff.

Here, because my ruby skills are sadly lacking, I am a little confused.

I figure that, when I understand how to do this sort of thing, that's broken the back of 90% of the database stuff I will need to know.

Suggestions and comments welcome.

Dave

Updated

Well this now works. Many thanks to Dayv Parry and some kind folks on the #roro IRC channel.

  class User < ActiveRecord::Base
    has_many :user_prefs
    def save_pref(name,value)
      pref = self.user_prefs.first(:conditions => {:name => name})
      if pref
        pref.update!(:value => value)
      else
        self.user_prefs.build(:name => name, :value => value)
      end
    end
    def get_pref(name)
      self.user_prefs.first(:conditions => {:name => name})
    end
  end
  class UserPref < ActiveRecord::Base
    belongs_to :user
    validates_uniqueness_of :name, :scope => :user_id
  end

Some people also pointed out that I could also use

  pref = self.user_prefs.find_by_name(name)

in place of

  pref = self.user_prefs.first(:conditions => {:name => name})

but it seems like much of a muchness to me.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

Frank is intended to be a very simple but feature complete web-app built on top of Sinatra that provides simple user login, password reminder, and user email verification with support for simple roles. It is intended to be used by other developers as both a well documented example of Sinatra in use, and a starting point for others wishing to implement simple web apps very quickly.

Shared Ticket Bins

v1.092% complete

 

Completed 22 of 24 tickets