activerecord

When to use association extensions vs named scopes?

From a cursory glance, they appear to be simply two different approaches to the same set of problems, except that named scopes are chainable, while association extensions are not. Can anyone explain further, or provide an example that would be more appropriate for an association extension than a named scope? ...

how to define a named_scope to roll up a has_many with nested models?

First the data model: class Forum < ActiveRecord::Base has_many :topics, :dependent => :destroy, :order => 'created_at desc' end class User < ActiveRecord::Base has_many :topics, :dependent => :destroy has_many :comments, :dependent => :destroy has_many :replies, :dependent => :destroy end class Topic < ActiveRecord::Base be...

Use ActiveRecord to Find Result of 5 Nested Tables

I have a User Model(:name, :password, :email), and Event model(:name, :etc) and Interest model (:name) Then I created two join tables -> UsersInterests and EventsInterests; each not containing a primary key and only comprised of the user_id/interest_id and event_id/interest_id respectively. I'm trying to use ActiveRecord to query a lis...

Custom ActiveRecord finder invoking named scopes?

I have a custom finder defined below: class ContainerGateIn << ActiveRecord::Base ... def self.search(text) result = if text text.split(' ').inject(self) do |result, criteria| case criteria when /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ result.search_by_date(criteria.to_date) else r...

ActiveRecord find query with join only doesn't include data from joined table

I have two tables: keyword_reports and keywords (with relevant AR models). keyword_reports has a keyword_id column, which I'm using to join the keywords table like so: KeywordReport.find(:all, :joins => :keyword, :conditions => {:page_id => 10}) which correctly pulls back records for keyword_reports, but doesn't include the data from...

Most code-efficient way to handle data stamped as "final" vs. data that may incur changes.

Hi there, I have several models whose records AND associations can have two states that must be persisted. Final, and Draft. Here's a little more detail: If the model is "application form" and the user submits a final application form, then I need to store and be able to retrieve that final application form. If, at a later date, the u...

Is it good practice to set a custom id value for an ActiveRecord object

I am writing a simple rails app that caches values from a web service. The web service returns a list of objects that look like this: <objects> <object> <id>12345</id> <name>obj name</name> </object> .... </objects> Is it okay to use the id coming in as the id for my ActiveRecord object if I am guaranteed ...

Why does ActiveRecord not use the primary_key and foreign_key columns when generating the SQL for a join in an association?

I know I can use :finder_sql to manually define the SQL to use to fetch associated records, but I'm wondering if ActiveRecord uses the :primary_key and :foreign_key options on an association to generate the joining SQL. It doesn't appear to, but am I just missing something here? Update: To be more explicit, my question is: Is there s...

Overload and Bypass Active Record Update

I am trying to implement an audit trail into my application, but because of some requirements I am unable to use any existing gems or plugins. I would like to divert any normal attempt to update a model to a custom method that saves all the updates in another separate Table (called Updates). The application then uses the update table t...

Rails: has_many, but also has_one by a different name

Let's say a User has many Documents, and a single Document they're currently working on. How do I represent this in rails? I want to say current_user.current_document = Document.first (with or without current_ in front of document) and have it not change the current_user.documents collection. This is what I have: class Document < Acti...

How can one obtain a row count from has_many :through relations with :uniq => true

This is my model: class Tag < ActiveRecord::Base # id, name has_many :taggings end class Tagging < ActiveRecord::Base # id, tag_id, owner_id, target_type, target_id belongs_to :tag belongs_to :owner, :class_name => 'User' belongs_to :target, :polymorphic => true validates_uniqueness_of :tag_id, :scope => [ :target_id, :ta...

How to handle failing migrations on reset because of deleted models/methods

An old one of my ruby on rails migrations contains both the actual migration but also an action to modify data: class AddTypeFlagToGroup < ActiveRecord::Migration def self.up add_column :groups, :selection_type, :string Group.reset_column_information Group.transaction do Group.all.each do |group| group.selection...

Rails - Adding Custom Fields at runtime in ActiveRecord

You know how some bug trackers (and other software) allow you to add custom fields? Typically this is done with a data structure that looks something like this: Items ---------- ID | NAME | ITEM_TYPE_ID FieldDefinitions --------------------------------------- ID | ITEM_TYPE_ID | FIELD_NAME | FIELD_TYPE FieldValues ------------...

Override type casting for ActiveRecord finder

I'd like to override the typecasting that ActiveRecord is doing to my datetime fields when using a finder like .first or .all but it doesn't seem to be working the way I thought it would.. I was expecting the override to return the datetime_before_type_cast like it works when I access the field directly in the bottom example. In my mode...

Rails: check if the model was really saved in after_save

ActiveRecord use to call after_save callback each time save method is called even if the model was not changed and no insert/update query spawned. This is the default behaviour actually. And that is ok in most cases. But some of the after_save callbacks are sensitive to the thing that if the model was actually saved or not. Is there a...

accepts_nested_attributes_for and nested_form plugin

Hi folks, I've the following code in a _form.html.haml partial, it's used for new and edit actions. (fyi I use the Ryan Bates' plugin nested_form) .fields - f.fields_for :transportations do |builder| = builder.collection_select :person_id, @people, :id, :name, {:multiple => true} = builder.link_to_remove 'effacer' ...

What is the fastest way to create mass HABTM associations in Rails?

...

How can I delete child objects when the parent is deleted in rails?

model a: has_many :b, :dependent => :delete_all model b: belongs_to :a belongs_to :c model c: has_many :b When I delete an a, I would also like to have children b's deleted so that they get removed from any c's that may reference them. However, the above isn't working. I'd appreciate any help. ...

Codeigniter - handling errors when using active record

Hi There, I am putting together a few models for my codeigniter site and can't seem to find any word in the documentation of how to handle errors that could occur when using the Active Record system. The documentation demonstrates how to perform CRUD along with some relatively involved queries but no where along the line is error handli...

db:seed not loading models

I'm trying to seed my database with the standard db/seeds.rb method. This works fine on my development machine, but on my server, I get: $ sudo rake db:seed RAILS_ENV=production --trace ** Invoke db:seed (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:seed rake aborted! uninitialized constant Permiss...