activerecord

How do I model these relationships?

I have a contact model, this includes name, address, phone number, etc. I have a user model which should have_one contact. I have a Customer model which has_many contacts. I have a Producer model which has many contacts. A contact can be only a user, a user and a customer, a user and a producer, or any combination of these three. I a...

Is it possible to run a find_by_sql query in Rails / ActiveRecord without loading all results into memory?

I'm building a Rails plugin that extracts a lot of data from Rails apps. It builds queries dynamically that span multiple tables, and there will be a lot of results returned. Here's an example of one of the queries built for pulling purchase data out of a Spree (Rails shopping cart): select orders.user_id as from_id, variants.product_id...

Finding an array of ids while keeping the order with Rails and PostGreSQL

Hi, I have an array of ids of objects that I want to get from the database, but PostGreSQL returns them sorted by ids: Users.find([4, 1, 3]) => [User 1, User 3, User 4] I know I could sort them back like this: ids = [4, 3, 1] r = Users.find(ids) users = ids.map{|id| r.detect{|each| each.id == id}} But wouldn't it be better if I co...

belongs_to through associations

Hi, can someone help me look at this. Getting too tired. class User has_many :questions has_many :choices end class Question belongs_to :user has_many :answers has_one :choice, :through => :answer end class Answer belongs_to :question end class Choice belongs_to :user belongs_to :answer belongs_to :question, :throug...

What's special about :conditions => [a_field IN (.., .., ..)] ?

The following result sets work well with will_paginate: Members.all(:limit => 5).paginate(:page => params[:page]) Members.all(:conditions => ["member_no < 6"]).paginate(:page => params[:page]) Members.all.paginate(:page => params[:page]) The following does not: Members.all(:conditions => ["member_no IN (?)", [1, 2, 3, 4, 5]]).paginat...

ActiveRecord (Rails 2.3.8) - Update existing, add new record when updating nested attributes

I have a "user" model that "has_one" "membership" (active at a time). For auditing and data integrity reasons, I'd like it so that if the membership changes for a user, the old/current record (if existing) has an inactive/active flag swapped, and a new row is added for the new changed record. If there are no changes to the membership, I'...

Jruby Activerecord is giving me stale connections

I have a Jruby app that spins up several background Java threads that share an ActiveRecord (2.3.5) connection. If they sleep for some time and then try to do something database related, the first queries never execute. I believe this is because the connections are stale, but the code itself doesn't throw any errors. I've tried doing ...

Singleton virtual model (Rails 3)

Hi, I would like to write a singleton virtual model (using Rails 3). Here is my code: class App extend ActiveModel::Naming include ActiveRecord::Associations include ActiveRecord::Reflection has_many :users def self.name 'MyApp' end end But that's not enough. If for instance I try this in Rails console: > App.firs...

Bulk update attribute on multiple models in ActiveRecord?

I have a simple has_many association, and I want to change an attribute from public to private the associated object. What's the best way to do this: class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user end user = User.first #=> #<User...> user.posts.count #=> 100 # something like t...

ActiveRecord - pre fetch single records from association

Consider the following models.. class Product < ActiveRecord::Base has_many :pricings end class Pricing < ActiveRecord::Base belongs_to :server end Pricing is a historical tracking table for prices of products, so there may potentially be hundreds of price points captured over time. What I want to add is a way to get only the...

I need to find closest date in a rails app.

Hi, I need to find the closest date to a given date using a rails named scope. With MySql I could use DATEDIFF but I want to keep database agnosticism, following doesn't work with Sqlite: named_scope :closest_to, lambda { |*args| date = args.first count = args[1] || 1 {:limit => count, :order => "ABS(DATEDIFF(hour, date_field, #...

Rails - serialize another activerecord model

I'm looking to serialize an incomplete/temporary model as an attribute of another model such as: class User < ActiveRecord::Base serialize :pending_post end Where pending_post is assigned an activerecord model: ... user.pending_post = Post.new(:title => "Whatever", :message => "whatever") user.save But instead of saving the yaml ...

Help with rails active record querying (like clause)

I want my code to do two things that is currently not doing @students = Student.where(["first_name = ? OR middle_name = ? OR last_name = ?", params[:query].split]) Work. (it says im supposed to pass 4 parameters but I want the user to be able to type words and find by those words on each of those fields and return whatever matches) A...

How do you optimize Castle ActiveRecord calls

How do you optimize ActiveRecord calls in your ASP.NET MVC 2 web applications ? I'm sitting in front of my project and all is fine until I start to fill in data. Like a lot of projects I have a data structure similar to this: A planet has many countries. A country has many states/provinces. A State has many cities. A city has many neig...

Cannot save text with double quotes in Rails ActiveRecord

I have this text. . . "I got them from the Wicked Witch of the East, when my house fell on her and killed her," she replied. "Where did you get the mark upon your forehead?" continued the voice. "That is where the Good Witch of the North kissed me when she bade me good-bye and sent me to you," said the girl. Again the ...

Is after_validation hook called every time on Active Record?

Is after_validation hook called every time, even when the validation is failed? I tried a couple tests and it seems like it! ...

ActiveRecord: change and save object state inside model

I have the following code: def incoming_acceptation(incoming_code) if invite_code == incoming_code accepted = true self.save true else false end end But it does not change and save accepted to true, it remains in the previous state, false. @i.incoming_acceptation(incoming_code) => true @i.accep...

rails 3, joining on more three tables

hello I would like joining more three tables in rails 3 my code class offer < ActiveRecord::Base belongs_to :user has_many :usercomments, :dependent => :destroy has_many :comments, :through => :usercomments, :dependent => :destroy end class User < ActiveRecord::Base has_many :usercomments, :dependent =>:destroy has_many...

rails 3.0.1 active_record

How is it possible with active_record? u = User.all u = u.where(:id => 1) NoMethodError: undefined method `where' for # u.class => Array Can't chain conditions :( ...

ActiveRecord repeating included associations in a query?

Hello all, In my app, I have three models: Markets, Deals, and Users. Relationships are pretty straightforward: class Market has_many :users has_many :deals end class User belongs_to :market end class Deal belongs_to :market end Now, in order to more easily query some of those relationships, the Market model has some metho...