Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11393 (closed defect: fixed)

Opened 6 months ago

Last modified 6 months ago

[PATCH] has_many :conditions should not only apply to :find but also :create

Reported by: tanman Assigned to: core
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: normal Keywords:
Cc:

Description

Assume I have a class Post. Post has a boolean field 'posted', indicating whether the post has been posted or not. I also have another class, Blog. If I want the blog to have many Posts:

class Blog < ActiveRecord::Base
    has_many :posts
    has_many :posted_posts, :conditions => {:posted => true}, :class_name => 'Post'
end

Blog.posted_posts.find(:all) works just as expected. But what if I want to do the following in order to have the blog post it immediately:

Blog.posted_posts.create(:title => 'The Blog Post')

This doesn't automatically alter the condition of :posted to true. This seems odd, and inconsistent since the only way to access this record is from Blog.posts, rather than Blog.posted_posts, where I created it from.

The obvious problem that arises is that if the conditions are not exactly specific about alterations need to be done such as 'date < 2008' the create cannot work with this. I suggest that to patch this, if a hash is being used for conditions it can be used on either a create or a find since the values are specific. Otherwise :conditions only applies to the find and an alternate :create_conditions can be used for creates.

Attachments

associations_respects_hash_conditions.diff (3.1 kB) - added by miloops on 03/21/08 17:18:23.

Change History

03/21/08 17:17:51 changed by miloops

  • summary changed from has_many :conditions should not only apply to :find but also :create to [PATCH] has_many :conditions should not only apply to :find but also :create.

I have noticed this before too and i'm glad to see someone else did. And yes, i also think it is inconsistent right now.

I attach patch that adds the functionality, tests included (to has_many and habtm).

03/21/08 17:18:23 changed by miloops

  • attachment associations_respects_hash_conditions.diff added.

03/21/08 18:22:00 changed by rick

  • status changed from new to closed.
  • resolution set to fixed.

(In [9068]) Allow association scoping for built/created records if :conditions is specified as a hash. Closes #11393 [miloops]