activerecord

How do I create/maintain a valid reference to a particular object in an ActiveRecord association?

Using ActiveRecord, I have an object, Client, that zero or more Users (i.e. via a has_many association). Client also has a 'primary_contact' attribute that can be manually set, but always has to point to one of the associated users. I.e. primary_contact can only be blank if there are no associated users. What's the best way to impleme...

TypeError Conversion on has_many relationship

I have a couple of objects in a Rails app ("Ticket", and "Comment") class Ticket < ActiveRecord::Base has_many :attributes has_many :comments end class Comment < ActiveRecord::Base belongs_to :ticket belongs_to :user end with the following schema: create_table "comments", :force => true do |t| t.integer "ticket_id" ...

Clean way to find ActiveRecord objects by id in the order specified

I want to obtain an array of ActiveRecord objects given an array of ids. I assumed that Object.find([5,2,3]) Would return an array with object 5, object 2, then object 3 in that order, but instead I get an array ordered as object 2, object 3 and then object 5. The ActiveRecord Base find method API mentions that you shouldn't expect ...

Implementing an ActiveRecord before_find

I am building a search with the keywords cached in a table. Before a user-inputted keyword is looked up in the table, it is normalized. For example, some punctuation like '-' is removed and the casing is standardized. The normalized keyword is then used to find fetch the search results. I am currently handling the normalization in the ...

Getting a NameError with ActiveRecord and relationships

I've run into a problem when using a one to many relationship. I want to have each Series have one Publisher and that one Publisher has many Series. This is my Publisher model: class Publisher < ActiveRecord::Base validates_presence_of :name has_many :series end This is my Serie model: class Serie < ActiveRecord::Base belongs_...

Under what circumstances will Active Record fail to enforce optimistic locking?

I watched in horror this morning as a script, running on two different machines, happily loaded, updated, and saved. I'm running ruby 1.8.6, AR 2.2.2. I started playing with some test cases and found reduced it to a minimal reproduction case: irb(main):059:0> first = Job.find :first => #<Job id: 323, lock: 8, worker_host: "second"> i...

Why does activerecord optimistic locking work only once per row?

Somehow, I always get these on Fridays. My earlier question was regarding the same problem, but I can now narrow things down a bit: I've been playing with this all day, trying to make sense of it. I have a table with a lock_version colum, specified thus: add_column :jobs, :lock_version, :integer, :default=>0 And I do something like...

Ruby On Rails Active Record question, related to has_one

I have a Show model that has_one :venue, which is accomplished with each show having a venue_id And my Venue model belongs_to :show However I am having a problem accessing the venue by doing show.venue Consider the following code where s is a Show instance logger.info("*********************") logger.info("#{s.inspect}") ...

Best practices for populating rails with processed data

I've been working for some months on a program for processing some data, and it's now at a stage where rather than displaying information (stored using ActiveRecord) via the command-line, I'd like to display the processed information via a Rails app. The first question I'm facing is whether I should have the data processing and the data...

AR.to_json Works in Console, Fails in Browser

I have this block of code: users = Array.new users << User.find(:all, :conditions => ["email like ?", "%foo%"]) users << User.find(:all, :conditions => ["name like ?", "%bar%"]) users.flatten! users.uniq! puts users.to_json :include => [:licenses] When I run it using script/console, it returns exactly what you would think it should, a...

multiple joins using activerecord in rails

I'm building a small twitter style microblogging service where users can follow other users and get a feed of their messages I have the following models: class Follow < ActiveRecord::Base belongs_to :follower, :class_name => "User" belongs_to :followee, :class_name => "User" end class User < ActiveRecord::Base has_many :follows,...

Rails ActiveRecord - is there a way to perform operations on tables without an id?

I have a table with one row and two columns- int 'version', datetime 'updated' Is there a Rails ActiveRecord way to get and set the data in these columns? There is no id column. I'm using this table to track versions of queries of other tables. After each query of another table the version column is incremented and the updated colum...

How do I get the name of a Ruby class?

How can I get the class name from an ActiveRecord object? I have: result = User.find(1) I tried: result.class # => User(id: integer, name: string ...) result.to_s # => #<User:0x3d07cdc>" I need only the class name, in a string (User in this case). Is there a method for that? I know this is pretty basic, but I searched both rails' ...

Why is there a discrepancy between ActiveRecord SQL and PL/SQL Developer SQL?

I have a select statement in Oracle PL/SQL Developer that's retrieving values based on a date: select * from <table> where to_date(create_date) = to_date('20090506', 'YYYYMMDD') where create_date is of Oracle type date. This returns a non-empty set as it should. However, in ActiveRecord: <Table>.find_by_sql("select * from <table> wh...

ActiveRecord: deleting associated records

Something I'm not getting... I have this in my model: class Model < ActiveRecord::Base has_many :model_options # a link table for many to many has_many :options, :through => :model_options, :dependent => :destroy, :foreign_key => 'model_id' end And I try to do this: model = Model.fin...

Using the same action to show all(index) objects, but also showing a list scoped by a url parameter

I'm having an issue coming up with a good way to do the following. I have a very generic Org model and User model. Org has_many :users, and User belongs_to :org. I am trying to find a way of showing a list of users that is not restricted by Org, but also show a list of User's that is restricted by Org. I know I could nest the routes, an...

has_one on a belongs_to in Rails?

I am building a rails site and am having trouble with the associations. Basically I have the following: class Publication < ActiveRecord::Base belongs_to :category has_one :site, :through => :category named_scope :on_site, lambda {|s| {:include => [:site], :conditions => ['sites.slug != ?', 's']}} end class Category be...

Active Record implementation of this SQL ?

I am using CodeIgniter. My database is MySQL 5. The SQL statement below works fine, but I am thinking it would not really be compatible with MSSQL, PG, et al. I am wondering if it's possible to implement the statement using the Active Record class in CI, hence making it completely cross database ? I think the "GROUP_CONCAT" is where I'l...

ActiveRecord MySQL and JOINS

Hey, I have a problem very similar to the one exposed here in RubyOnRails Guide. This query : Client.all :joins => :orders, :conditions => { :orders => {:created_at => time_range}} should return all the clients with their orders if they made some orders within the time range. Am I right? What I want is slightly differen...

Updating the db 6000 times will take few minutes ?

I am writing a test program with Ruby and ActiveRecord, and it reads a document which is like 6000 words long. And then I just tally up the words by recordWord = Word.find_by_s(word); if (recordWord.nil?) recordWord = Word.new recordWord.s = word end if recordWord.count.nil? recordWord.count = 1 else recordWord.count += 1 end r...