activerecord

executing named_scoped only when there are present params

Hi have a model like this: class EventDate < ActiveRecord::Base belongs_to :event named_scope :named, lambda { | name | { :joins => { :event => :core}, :conditions => ["name like ?", "%#{ name }%"] }} named_scope :date_range, lambda { | start, length | { :conditions => ["day >= ? AND day <= ?", start, date + (lengt...

Dynamic find methods Vs conditional statements

Student.find(:all, :conditions => [‘name = ? and status = ?’ ‘mohit’, 1]) Vs Student.find_all_by_name_and_status(‘mohit’, 1) Both the queries will result the same set of row but first one is preferable cause in the second way there will be exception generated method_missing and then rails will try to relate it as dynamic method. if ...

In Ruby on Rails, does changing to_param() have any side effect and what ways can be used to change it?

In some book, it is recommended that to_param is changed to class Story < ActiveRecord::Base def to_param "#{id}-#{name.gsub(/\W/, '-').downcase}" end end so that the URL is http://www.mysite.com/stories/1-css-technique-blog instead of http://www.mysite.com/stories/1 so that the URL is more search engine friendly. So...

Using named_scope with counts of child models

Hi, I have a simple parent object having many children. I'm trying to figure out how to use a named scope for bringing back just parents with specific numbers of children. Is this possible? class Foo < ActiveRecord::Base has_many :bars named_scope :with_no_bars, ... # count of bars == 0 named_scope :with_one_bar, ... # cou...

ActiveRecord Validations for Models with has_many, belongs_to associations and STI

I have four models: User Award Badge GameWeek The associations are as follows: User has many awards. Award belongs to user. Badge has many awards. Award belongs to badge. User has many game_weeks. GameWeek belongs to user. GameWeek has many awards. Award belongs to game_week. Thus, user_id, badge_id and game_week_id are foreign...

Rails: three most recent comments with unique users

what would I put in the named scope :by_unique_users so that I can do Comment.recent.by_unique_users.limit(3), and only get one comment per user? class User has_many :comments end class Comment belongs_to :user named_scope :recent, :order => 'comments.created_at DESC' named_scope :limit, lambda { |limit| {:limit => limit}} na...

Designing Web Service Using Ruby on Rails - Mapping ActiveRecord Models

I've put together a RoR application and would now like to publish a RESTful web service for interacting with my application. I'm not sure where to go exactly, I don't want to simply expose my ActiveRecord models since there is some data on each model that isn't needed or shouldn't be exposed via an API like this. I also don't want to c...

need an empty string, but getting an exception in ruby on rails

controller @articles = current_user.articles view <% @articles.each do |article| %> <%= link_to "#{article.title} , #{article.author.name}" articles_path%> <% end %> Sometimes the article has no author, so is null in the database, which results in the following error You have a nil object when you didn't expect it! The error occ...

Prevent a Rails model from saving

I have a scenario where I have a model that I want to populate and validate against, but don't necessarily want to write down to the database when it's parent object is. For instance, let's say I have an account and a credit card model, the credit card is built against the account, and validated when the account is, but also saved when ...

ActiveRecord: issue with 'find' method when querying dates.

I'm struggling with the conditions for date querying in the 'find' method on my ActiveRecord models running over an SQLite3 database. My model is as follows: Day: failure_day: date failure_count: integer When I attempt to query Days, I get the following (pseudo code only): Query: Days.all Result: [{failure_day: 2010-04-14,...

Complex queries using Rails query language

I have a query used for statistical purposes. It breaks down the number of users that have logged-in a given number of times. User has_many installations and installation has a login_count. select total_login as 'logins', count(*) as `users` from (select u.user_id, sum(login_count) as total_login from user u ...

ActiveRecord WHERE NOT EXISTS

Is there a way to use EXISTS with ActiveRecord besides find_by_sql? I'd like a nice way to find all records without an association in a One-to-Many relationship. SELECT DISTINCT store_type FROM stores WHERE NOT EXISTS (SELECT * FROM cities_stores WHERE cities_stores.store_type = stores.store_type) ...

Find by Quantity

Let's say I have a model Vehicle and it has_many :wheels What is the correct find / :conditions => ... statement to find only vehicles with 3 or more wheels, e.g. tricycles, cars, trucks, tanks etc...? ...

ruby-on-rails3, and select distinct using activereccord3

Hi, Some methods have been deprecated with Rails3. It is the case in particular with the following call ! Error.find(:all, :select => 'DISTINCT type') Is anybody have an idea, how to convert this call to an ActiveRecord3 valid statement ? I found nothing on the web ... Thanks ...

What's the proper way to override Rails ActiveRecord creation/deletion events in a subclass, such as after_create

Hi, I have a class heirarchy as follows: class A < ActiveRecord::Base after_create { |i| #do something } end class B < A after_create { |i| #do something else after what A did } end I want to have A's behavior performed in B when after_create is invoked, but I am not sure of the proper way to write the after_create me...

Rails/SQl query help: Find all by created_at in past 7 days per each day?

I'm unable to get SQL and Rails to play properly when trying to find Categories that are created each day, the past 7 days. So basically I want to find each Category sorted by the day they were created for the past 7 days. I found this on stackoverflow, but it isn't finding a Category that I just created: Category.all(:conditions => [...

NULL value in :conditions =>

Contract.all(:conditions => ['voided == ?', 0]).size => 364 Contract.all(:conditions => ['voided != ?', 0]).size => 8 Contract.all.size => 441 the 3 numbers does not added up (364 + 8 != 441). What's the proper way write the :conditions to count the rows which the voided column value is NULL or equal to zero? ...

Rails Habtm with a field

Hello, Is that possible to have a field in a has and belongs to many table? Just like favorite: create_table :messages_users, :id => false, :force => true do |t| t.integer :message_id, :null => false t.integer :user_id, :null => false t.boolean :favorite, :null => false t.timestamps end I saw timestamps works well, thanks ...

how to get record created today by rails activerecord?

How to write the :condition statement if I would like to get all the record which are created today? ...

RAILS : What is cached when using config.cache_classes = true

Hi, I was just wondering and didn't find explicit response on what in the model class (ActiveRecord) is cached when setting config.cache_classes to true ? Could someone tell me or point me to the doc I didn't found ? Thanks ...