activerecord

Broken foreign keys in Rails

So here's a quick question. I'm using Rails with a huge legacy database, and it has many broken foreign keys that need to be treated as nils. So when I do: Foo.find(:all, :conditions => {...}, :include => :bar) Rails with connect all bars with SELECT * FROM bars WHERE id IN (...). So far so good, just two sql queries. Now the problem ...

Rails: Script to import data

I have a couple of scripts that generate & gather large amounts of data that I will need both to seed my database with and in the future to add large amounts more to it. What is the best way to import lots of relational data into a rails database as both seed data and intermittently during production? I haven't settled on an output for...

Ruby on Rails ActiveRecord conditional validation (and more..)

I have a Product model which validates multiple attributes (including a Paperclip image attachment) like so: validates_presence_of :name validates_format_of :name, :with => /^([a-zA-Z0-9\ \-]{3,128})$/i ... has_attached_file :image validates_attachment_presence :image validates_attachment_content_type :image, :content_type => ["image/j...

How to get rails to return SUM(columnName) attributes with right datatype instead of a string?

Assume a query of the following form operatingExpenses = Expense.find(:all, {:select=>"categories.activityType, categories.name heading, sum(amount) totalAmount", :joins => "inner join expense_categories categories on category_id = categories.id ", :group => "categories.activityType, categories.name", :order => "...

Rails and ActiveRecord: Save a parent object while using find-or-create on has-many children

I am trying make a complex form (like the railscast) with repeated-auto-complete (modified by Pat Shaughnessy) work for creating articles with many authors (has-many :through). I've got it working as long as I willing to always create new authors when I save an article. How can I get my associated author records to only be created wh...

Select columns from two or more tables using ActiveRecord in asp.net

Using ActiveRecord in asp.net is it possible to select columns from two or more tables together to show information in grid as a single record? For example if I have two models (1) product model contains ID, ProductName, Price properties and (2) order model contains OrderID, ProductID, Quantity. I need to retrieve data(load) from both m...

ORM: OneToOne mapping on Non Primary-Key Join column - Book and Inventory mapped by ISBN

I have a Book model and Inventory model mapped by ISBN number, but ISBN is not the primary key in either. Books belong to Bookstores and Inventory is for a group of Bookstores(BookstoreChain). Inventory is shared by all Bookstores belonging to a BookstoreChain. I'm using Hibernate @OneToOne mapping on the book side to fetch inventory i...

Rails ActiveRecord: Inserting text containing unprintable/weird characters

I am inserting some text from scraped web into my database. some of the fields in the string have unprintable/weird characters. For example, if text is "C__O__?__P__L__E__T__E", then the text in the database is stored only as "C__O__" I know about h(), strip_tags()... sanitize, ... etc etc. But I do not want to sanitize this SQL. Th...

Find newest objects in ActiveRecord

Easy question: I need help writing an ActiveRecord find_all_by statement where I want to order things from newest created objects to oldest. As a follow-up to this question: If I saved the results into a variable @records. How do I then ask for the next record in it? I want to do something like @current_record = @records.next ...

ActiveRecord - querying polymorphic associations

I am using polymorphic associations to track Comments in my project. All very straight forward stuff. The problem I have is in querying based on the polymorphic association and joinging from the Comment model back to it's owner. So ... I have a Comment model class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic ...

Adding further attributes to a ActiveRecord serialization?

I have my json serialization working fine render :json => "#{current_object.serialize(:json, :attributes => [:id, :name])} But I also want to add further data to the json before it gets set back to the client. Mainly the auth_token. Googled around like crazy but I can not find what option serialize will take to allow me to append/me...

Activerecord - callback after all associated objects are saved

I have a model and I would like to store ids of associated objects (denormalize) for performance reasons. I have a method which looks like this: def cache_ids self._tag_ids = self.tag_ids end I thought I could just run it on before_save, however there is a problem - some of the associated objects might be new records, and therefore ...

Get ids of elements in a named scope

In ruby on rails, all has_many :widgets methods generate both a object.widgets method and an object.widget_ids method. The latter method is very useful because it bypasses the creation of ActiveRecord objects and runs a much faster query. The query speed can be improved by using the :select option, but ruby still allocates much more mem...

ActiveRecord: Can I copy associations?

Is there a way to copy the associations of one model to another... template_model = MyModel.find(id) new_model = template_model.clone new_model.children << template_model.children # I want to *copy* children ...such that I copy the children from the template to the new model? (In fact this code moves children from the template to the ...

Rails join table renders bad sql

UPDATED: to include model relationships I have a many to many join table between Bands and Events (an event has many bands, a band has many events...) I have a main page that lists all events, and a recent page which displays events updated in the past 7 days. Could someone explain why the recent method generates perfect sql with all ...

Rails Resource Restful Routes Helper functions and nil oject error

Hello I am getting an error when trying to use the resource route helper functions <%= link_to_remote "Delete", { :method => :delete, :url=> phone_numbers_url(phone_number_display.id), :update => "section_phone" }%> and in my routes i have map.resources :phone_numbers I get the following error You have a nil o...

Rails ActiveRecord Relationships

How do the relationships magically function when only the models are altered? If I want a "has__and___belongs___to__many" relationship, what should I name the table (so Rails can use it) that contains the two foreign keys? ...

Rails Migration

My migration is as follows: class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :email t.string :password t.string :name t.boolean :male t.boolean :admin t.timestamps end end def self.down drop_table :users end end When I go to script/con...

Activerecord: Finding non associated plus associated records with a single query

Given the following scenario, using activerecord: User belongs_to Event I want to find all the Users who do not have an Event with the name "party". So I tried the following: User.all(:joins => :event, :conditions => ["events.name != ?", "party"]) However, that will only return those Users who do have an event, but just not a "part...

my_object.save(false) doesn't REALLY skip my Active Record validations

Hey All, So I have been pulling my hair out troubleshooting this bug I have been having, and I finally discovered what was causing it. I had always been under the impression that when I called @my_model.save(false) That I would be skipping my ActiveRecord validations. Turns out this is partially true. My objects are saving to the d...