Coder Social home page Coder Social logo

acts_as_relation's People

Contributors

den-sheleh avatar dgalarza avatar hzamani avatar jfrux avatar lowjoel avatar nikhgupta avatar sabarish-soft avatar schuetzm avatar wharle90 avatar wjgilmore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

acts_as_relation's Issues

Some methods not inheriting

Having some very strange issues with regards to child classes inheriting some parent methods

Here is one of the offending methods in my parent class:

def first_reccord
self.profiled_appliances.first.first_reccord
end

here is my console readout:
x = Parent.first
y = Child.first
x.specific == y # true
x.first_record #
y.first_reccord # NoMethodError: undefined method 'first_reccord' for

I don't understand why this is happening? Other parent methods are inheriting fine.

Find or build methods are not supported

This line completes without errors, but create an empty model, i.e. the attributes in the where query are not included:
SubModel.where("attribute = ?", 'value').first_or_create!

And this line throws an exception:
SubModel.find_or_create_by(attribute: value)

Cannot instantiate an subclass

I have my classes all set up, but i cannot instantiate a subclass. Here is what i am getting:

[1] pry(main)> AssemblyTypeItem.create :name => 'this is it'

NoMethodError: undefined method update' for #<ActiveModel::MassAssignmentSecurity::WhiteList: {}> from /Users/xxx/.rvm/gems/ruby-1.9.3-p448/gems/acts_as_relation-0.1.2/lib/active_record/acts_as_relation.rb:106:inincluded'

anyone have any ideas? thanks in advance..

here is what everything looks like:

environment
rails (3.0.20)
acts_as_relation (0.1.2)
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.5.0]

classes
class Item < ActiveRecord::Base                                                                                                                                                                                                             
   acts_as_superclass
   attr_accessible :type, :name, :key
end

class AssemblyTypeItem < ActiveRecord::Base
   acts_as :item
   attr_accessible :comment
end

schema
create_table "assembly_type_items", :force => true do |t|
     t.string   "comment"
     t.datetime "created_at"
     t.datetime "updated_at"
end

create_table "items", :force => true do |t|                                                                                                                                                                                             
     t.integer  "as_item_id"
     t.string   "as_item_type"
     t.string   "name"
     t.string   "key"
     t.string   "description"
     t.datetime "created_at"
     t.datetime "updated_at"
 end

N+1 Query detected

Hi!
How can I prevent N+1 queries?
I have the following models

class Client < ActiveRecord::Base
  acts_as_superclass
end

class Buyer < ActiveRecord::Base
  acts_as :client, include: true
end

class Seller < ActiveRecord::Base
  acts_as :client, include: true
end

Every time I search for Buyers or Sellers, the bullet gem warns me about N+1 queries detected as it follows:

N+1 Query detected
  Provider => [:client]
  Add to your finder: :include => [:client]
N+1 Query method call stack
  N+1 Query method call stack
  N+1 Query method call stack
  N+1 Query method call stack
  N+1 Query method call stack
  N+1 Query method call stack

I've tried with this param

class Provider < ActiveRecord::Base
  acts_as :client, include: :client
  ...

And even overriding the default_scope like this

class Provider < ActiveRecord::Base
  default_scope include: :client
  ...

But it keeps me giving me the same warning.
What am I doing wrong?
Thanks in advance!

Parent.specific returns nil

Hi! I'm trying to integrate acts_as_relation with Devise and CanCan, so I have the following models:

class User < ActiveRecord::Base
  rolify
  acts_as_superclass
  ....
end

class UsuarioBanco < ActiveRecord::Base
  acts_as :user, as: :usuario
  ....
end

Everything regarding acts_as_relation works fine, until I define de abilities in my bbility.rb

class Ability
  include CanCan::Ability
  def initialize(user)
    if user.es_banco?
      can [:read, :update], Banco, id: user.specific.banco_id
    end
  ....
end

My user.specific returns nil, instead of a UsuarioBanco instance... I've been using your gem in another projects, not using it with Devise models, and this worked fine.
Do I have anything wrong?
Thanks in advance!

Create does not work on parent object attributes with validation

Disclaimer: This issue might be related to #9, although I'm not sure it is.

Let's say I have a Project model that has many items, the Item model being polymorphic.

class Project < ActiveRecord::Base
  # ...

  has_many :items
  has_many :bookmarks, :through => :items, :source => :postable, :source_type => "Bookmark"
  has_many :notes, :through => :items, :source => :postable, :source_type => "Note"
  has_many :tasks, :through => :items, :source => :postable, :source_type => "Task"
end

class Item < ActiveRecord::Base
  acts_as_superclass
  attr_accessible :title, :description, :project_id, :postable_type, :postable_id
  belongs_to :postable, :polymorphic => true
  validates :title, :presence => true
end

Now, when I define a Bookmark model like so:

class Bookmark < ActiveRecord::Base
  acts_as :item, :as => :postable
  attr_accessible :favicon, :url
  validates :url, :presence => true
end

And try to create one for a specific project in the console, it fails with a validation error on the common attribute, which was provided in the create statement:

p.bookmarks.create!(:title => "Foo Bar", :url => "http://www.foobar.com")
   (0.3ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "bookmarks" ("created_at", "favicon", "updated_at", "url") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", Wed, 26 Sep 2012 13:28:49 UTC +00:00], ["favicon", nil], ["updated_at", Wed, 26 Sep 2012 13:28:49 UTC +00:00], ["url", "http://www.foobar.com"]]
  SQL (0.5ms)  INSERT INTO "items" ("created_at", "description", "postable_id", "postable_type", "project_id", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["created_at", Wed, 26 Sep 2012 13:28:49 UTC +00:00], ["description", nil], ["postable_id", 5], ["postable_type", "Bookmark"], ["project_id", nil], ["title", "Foo Bar"], ["updated_at", Wed, 26 Sep 2012 13:28:49 UTC +00:00]]
   (0.3ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Title can't be blank

However, if I use new then save, it works flawlessly:

bookmark = p.bookmarks.new(:title => "Foo Bar", :url => "http://www.foobar.com")
   (0.3ms)  BEGIN
   (0.2ms)  COMMIT
 => #<Bookmark id: nil, url: "http://www.foobar.com", favicon: nil, created_at: nil, updated_at: nil> 
bookmark.save!
   (0.3ms)  BEGIN
  SQL (0.5ms)  INSERT INTO "bookmarks" ("created_at", "favicon", "updated_at", "url") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", Wed, 26 Sep 2012 13:32:44 UTC +00:00], ["favicon", nil], ["updated_at", Wed, 26 Sep 2012 13:32:44 UTC +00:00], ["url", "http://www.foobar.com"]]
  SQL (0.5ms)  INSERT INTO "items" ("created_at", "description", "postable_id", "postable_type", "project_id", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["created_at", Wed, 26 Sep 2012 13:32:44 UTC +00:00], ["description", nil], ["postable_id", 6], ["postable_type", "Bookmark"], ["project_id", nil], ["title", "Foo Bar"], ["updated_at", Wed, 26 Sep 2012 13:32:44 UTC +00:00]]
   (2.1ms)  COMMIT
 => true

I take it that the parent class methods are made available to the child model object during its initialization. Is there a workaround to this issue? Could it be related to issue #9?

Thanks in advance.

Association Type Mismatch error

I'm having a strange issue with acts_as_relation. I have my (simplified) models structure as follows:

class User < ActiveRecord::Base
  has_one :occupation
end

class Occupation < ActiveRecord::Base
  acts_as_superclass

  belongs_to :user
  validates :user_id, presence: true
end

class Worker < ActiveRecord::Base
  acts_as :occupation, as: :occupation
end

In my migration, I used

  create_table "occupations", force: true do |t|
    t.integer "occupation_id"
    t.string  "occupation_type"
    t.integer "user_id"
  end

With this hierarchy (very similar to bigardone's one), I was expecting to be able to do the following simple assignment

user.occupation = Worker.new

however I'm getting this error:

ActiveRecord::AssociationTypeMismatch: Occupation expected, got Worker

I realised that you don't actually say this is possible anywhere in the docs, but I thought it would be. Currently, I'm working around this as follows:

user.occupation = Worker.new.occupation

which feels a bit like a hack.

I understand this is a very basic question, but I am relatively new to Rails, so I am wondering if I'm missing something?

Migrations issue

Hi guys,

Am having an issue and i don't know what is going on, after i added the gem act_as_relation when i try to run the migrations am having this error

bundle exec rake db:setup
rake aborted!
PG::Error: ERROR: relation "products" does not exist
LINE 5: WHERE a.attrelid = '"products"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"products"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

I have a product model that act as a superclass, and i have two other models than acts as products.

If i comment out the lines that calls the gem:
acts_as_superclass
acts_as :product

The migrations works again

what could be the error?

Nested use with factory girl causes `Segmentation fault`

I've this structure.

class StaticPlaylist < ActiveRecord::Base
  acts_as_superclass
end

class ImportedPlaylist < ActiveRecord::Base
  acts_as :static_playlist
  acts_as_superclass
end

class DigiPlaylist < ActiveRecord::Base
  acts_as :imported_playlist
end

When I try creating a DigiPlaylist using factory girl I get this error.

<ruby-root>/gems/acts_as_relation-1.0.0/lib/active_record/acts_as_relation.rb:83: [BUG] Segmentation fault
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]

-- Crash Report log information --------------------------------------------
   See Crash Report log file under the one of following:
     * ~/Library/Logs/CrashReporter
     * /Library/Logs/CrashReporter
     * ~/Library/Logs/DiagnosticReports
     * /Library/Logs/DiagnosticReports
   the more detail of.

-- Control frame information -----------------------------------------------
<ruby-root>/gems/acts_as_relation-1.0.0/lib/active_record/acts_as_relation.rb:83: [BUG] Segmentation fault
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]

-- Crash Report log information --------------------------------------------
   See Crash Report log file under the one of following:
     * ~/Library/Logs/CrashReporter
     * /Library/Logs/CrashReporter
     * ~/Library/Logs/DiagnosticReports
     * /Library/Logs/DiagnosticReports
   the more detail of.

Here is the full stacktrace.
It looks like an infinitive loop.

My factory looks like this.

FactoryGirl.define do
  factory(:digi_playlist) do
  end
end

I looks like the problem is explained in pull request #8.

endless loop at time of creation in some cases (as example creation through Factory Girl Proxy)

How can we solve this?

AR has_one association broken?

In 1.0.0, the following in lib/active_record/acts_as_relation.rb (line 65) breaks using AR 3.2.13:

            singleton.send :define_method, :included do |base|
              base.has_one name.to_sym, scope, has_one_options

has_one accepts two arguments, so this raises an ArgumentError (wrong number of arguments (3 for 2)).

Cannot use created_at or any timestamp columns to query: ambiguous column name

Fell into another issue here with acts_as_relation. From the dummy project in the acts_as_relation code, I run the migrations and then created a few objects. However, it's not possible to execute a query like this:

Pencil.where("created_at <= ?", Date.new())

You get an "ambiguous column name" error. Other than removing the created_at and updated_at columns on the subclasses or parent class, is there another way to get around this?

Rails 3.2 - .specific is not working?

Upfront, I'm using ruby 1.9.3 and rails 3.2.15. Also, using the '~>0.1' modifier on my gemfile.

Have 2 simple models:

class Person < ActiveRecord::Base
  belongs_to :country
  belongs_to :affiliation, :class_name => "Entity"

  attr_accessible :active, :email, :name, :personizable_id, :personizable_type, :phone, :shortcv, :url  
  acts_as_superclass
end

class Member < ActiveRecord::Base
  belongs_to :position
  belongs_to :function
  attr_accessible :alias, :bibtext_name, :cv, :order, :photo, :sname, :state

  acts_as :person, :as => :personizable
end

The person migration includes:

    create_table :people do |t|
      t.integer :personizable_id
      t.string :personizable_type
    end

From the rails console i'm able to do:

m = Member.first
m.name (an attrib from Person)

But can't do:

p = Person.first
p.specific (returns nil)

The specific db entry has the correct ID and personizable_type as 'Member'

Any help please?

Nested form splitting child records across multiple rows

Every time I create a nested object that uses multiple table inheritance, two different rows is created for the child object.

I have a has_many relationship between my store and products object and using multiple table inheritance to represent books and other types of products. Every product has a cost attribute and belongs to a store.

class Store < ActiveRecord::Base
    has_many :products, :dependent => :destroy
    has_many :books, :through => :products, :source => :as_product, :source_type => "Book"
    accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank
    accepts_nested_attributes_for :books, :allow_destroy => true, :reject_if => :all_blank
end

class Product < ActiveRecord::Base
     acts_as_superclass
     belongs_to :store
end

class Book < ActiveRecord::Base
     belongs_to :store
     acts_as :product, :include => true
end

When I build a store and nested products via a formtastic form, I end up getting these rows:

+----+----------+---------------+-----------------+------+
| id | store_id | as_product_id | as_product_type | cost |
+----+----------+---------------+-----------------+------+
| 45 |     NULL | 29            | Book            |   17 |
| 46 |       39 | 29            | Book            | NULL |
+----+----------+---------------+-----------------+------+

The association and attribute (cost) gets split across two rows. Any ideas?

The params passed through the form looks normal to me:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"aHmLdcXZxW/BSU0XIbW7PwGWXNJ2cX42NtMkDCEN7GE=", "store"=>{"name"=>"Borders", "books_attributes"=>{"0"=>{"author"=>"Gaiman", "cost"=>"17.0", "_destroy"=>"false"}}}, "commit"=>"Create Store"}

Migration error with eager loading

Enabling causes migrations to fails

config.eager_load = true

With the following trace

rake aborted!
PG::UndefinedTable: ERROR:  relation "users" does not exist
LINE 5:                WHERE a.attrelid = '"users"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = '"users"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql_adapter.rb:768:in `exec'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql_adapter.rb:768:in `exec_no_cache'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:138:in `block in exec_query'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract_adapter.rb:425:in `block in log'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract_adapter.rb:420:in `log'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:137:in `exec_query'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql_adapter.rb:915:in `column_definitions'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/postgresql/schema_statements.rb:174:in `columns'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/schema_cache.rb:114:in `block in prepare_default_proc'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/schema_cache.rb:56:in `yield'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/schema_cache.rb:56:in `columns'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:208:in `columns'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:253:in `content_columns'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/lib/active_record/acts_as_relation.rb:70:in `block (2 levels) in acts_as'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/lib/active_record/acts_as_relation.rb:112:in `include'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/lib/active_record/acts_as_relation.rb:112:in `block in acts_as'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/lib/active_record/acts_as_relation.rb:111:in `class_eval'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/lib/active_record/acts_as_relation.rb:111:in `acts_as'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/app/models/student.rb:10:in `<class:Student>'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/app/models/student.rb:1:in `<top (required)>'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `block in require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:329:in `require_or_load'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:288:in `depend_on'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:206:in `require_dependency'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:465:in `block (2 levels) in eager_load!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:464:in `each'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:464:in `block in eager_load!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:462:in `each'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:462:in `eager_load!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:347:in `eager_load!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/finisher.rb:56:in `each'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `instance_exec'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `run'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:55:in `block in run_initializers'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:54:in `run_initializers'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:215:in `initialize!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in `method_missing'
/home/achachiez/Code/Rails/Projects/Bespoke/bespoke_college/config/environment.rb:5:in `<top (required)>'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `block in require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:189:in `require_environment!'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:249:in `block in run_tasks_blocks'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in `eval'
/home/achachiez/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in `<main>'
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)

But eager loading should be enabled in production. Thanks for the good work. Please suggest how I can fix this or fix it.

Unknown Attribute on child model

I am trying to create a structure similar to the instructions however I seem to be running into an issue with an attribute it expects.

Here is my parent migration:

create_table :payment_methods, :as_relation_superclass => true do |t|
    t.boolean :is_default
    t.integer :user_id
    t.timestamps
 end

My models:

class PaymentMethod < ActiveRecord::Base
  attr_accessible :user_id, :is_default

  acts_as_superclass
end

class CreditCard < ActiveRecord::Base
  attr_accessor :brand, :name, :token

  acts_as :payment_method, include: true
end

But the error I keep receiving is:

$> CreditCard.new
ActiveRecord::UnknownAttributeError: unknown attribute: as_payment_method_id
from SOME_DIRECTORY/gems/activerecord-3.2.13/lib/active_record/attribute_assignment.rb:88:in `block in assign_attributes'

Any idea what I could be doing wrong?

additional producible columns

Hello, this gem works to me but i need somehow recognize if Pen is at the same time Tee .. (Bar/Restaurant) i thought workaround with

change_table :products do |t|
t.integer :producible_id
t.string :producible_type

t.integer :producible2_id
t.string :producible2_type
end

class Pen < ActiveRecord::Base
acts_as :product, :as => :producible
end

class Book < ActiveRecord::Base
acts_as :product, :as => :producible2
end

will work but it doesnt, maybe normal references is only chance for me

has_many :somethings << failing

Given these models:

class User < ActiveRecord::Base
  has_many :message_sources
end

class MessageSource < ActiveRecord::Base
  acts_as_superclass

  belongs_to :user, polymorphic: true
end

class TwitterMessageSource < ActiveRecord::Base
  acts_as :message_source
end

When I

User.first.message_sources << TwitterMessageSource.new()

I get:

MessageSource(#70179625865060) expected, got TwitterMessageSource(#70179625930940)

Trying to use acts_as_relation and getting unexpected results.

I have the following relationships via acts_as_relation:

class Node < ActiveRecord::Base
  acts_as_superclass
  belongs_to :game, polymorphic: true
  #...
end

class Game < ActiveRecord::Base
  acts_as :node
  has_many :ancestors, class_name: 'Node',
           foreign_key: 'ancestor_id'
  #...
end

class Team < ActiveRecord::Base
  acts_as :node
  # ...
end

When I add a Game to the list of ancestors in another Game, I get:

ActiveRecord::AssociationTypeMismatch: Node(#30169720) expected, got Game(#24699180)
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/association.rb:204:in `raise_on_type_mismatch'
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/collection_association.rb:494:in `block in concat_records'
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/collection_association.rb:493:in `each'
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/collection_association.rb:493:in `concat_records'
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/collection_association.rb:132:in `concat'
/home/rev/.rvm/gems/ruby-1.9.3-p385@global/gems/activerecord-3.2.12/lib/active_record/associations/collection_proxy.rb:116:in `<<'
/home/rev/RubymineProjects/AliasMadness/app/models/bracket_factory.rb:17:in `block in create_bracket'

If I examine the Game object in the debugger, object.is_a? Node returns false, which makes no sense, given the above.

Do you have any suggestions for how I can proceed? This is rails 3.2.12 under ruby 1.9.3.

Pen.where(name: "...") doesn't work

This might be an edgecase –– since Pen.where("name = ?", "...") is still working –– but I think this API is pretty widely used and would be cool to be able to use it.

Edit: just to be clear, I meant to write the subclass, not the superclass, in the issue title. This call from the superclass does in fact work.

unknown attribute: as_user_id [HELP]

Hi All,

I would implement Acts_as_relation gem, but I have some difficult to do it.
I have Users and Students, all students are users.
I'm using rails 3 and SQLite

Here is my code :

class User < ActiveRecord::Base
  acts_as_superclass
  attr_accessible :uid, :name, :surname, :idperson, :created_at, :updated_at, :subtype,
end

class Student < ActiveRecord::Base
  acts_as :user
  attr_accessible :titel, :birth, :origin, :last_connected_at
end

My migration file :

class AddRelationSuperclass < ActiveRecord::Migration
  def change
    change_table :users, :as_relation_superclass => true do |t|

    end
  end

  def down
  end
end

But now, when I create a student, I have always this error message :

 - ActiveRecord::UnknownAttributeError: unknown attribute: as_user_id

As it's explained in the wiki, the migration :

change_table :users, :as_relation_superclass => true do |t|

end

should add a foreign key in the user table, right ?

How can I solve this ?

Please help me !!

Many thanks in advance

Nicolas

Mass Assignment Error of Child Attributes

I am trying to call update_attributes on a child object but everytime I call it, it throws a mass assignment issue. I have the attr accessible set for the attribute on the child model but it only seems to work if i set it on the parent.

Here is my parent model:

class PaymentMethod < ActiveRecord::Base
  attr_accessible :user_id, :is_default

  acts_as_superclass

  belongs_to :user
end

My child model:

class CreditCard < ActiveRecord::Base
  attr_accessible :brand, 
    :name, :token, :as_payment_method_id
  acts_as :payment_method
end

And my db schemas:

create_table :payment_methods, :as_relation_superclass => true do |t|
  t.boolean :is_default
  t.integer :user_id

  t.timestamps
end

create_table :credit_cards do |t|
  t.string :name
  t.string :brand
  t.string :token

  t.timestamps
end

There exact error I get is:

$> CreditCard.first.update_attributes(:brand => "123")

CreditCard Load (1.0ms) SELECT "credit_cards".* FROM "credit_cards" INNER JOIN "payment_methods" ON "payment_methods"."as_payment_method_id" = "credit_cards"."id" AND "payment_methods"."as_payment_method_type" = 'CreditCard' LIMIT 1
PaymentMethod Load (0.5ms) SELECT "payment_methods".* FROM "payment_methods" WHERE "payment_methods"."as_payment_method_id" = 3 AND "payment_methods"."as_payment_method_type" = 'CreditCard' LIMIT 1
(0.2ms) BEGIN
(0.3ms) ROLLBACK
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: brand
from /Users/nephtalirodriguez/.rvm/gems/ruby-1.9.3-p125@tutonic/gems/activemodel-3.2.13/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'

So the issue lies in the child(CreditCard) returning payment method instead of CreditCard. If I was to remove the acts_as :payment_method, it updates fine but then as expected, doesn't have the attributes of it's parent. Any idea what I could do to fix this?

Circular reference issue when running migration

I sure hope someone else has this problem!

We've been using this gem for several months to provide common functionality to several of our models without having lots of duplicated data and empty tables, but we encountered a problem when we first tried adding the table for the common parent table. Namely, when trying to add our parent model (TaggedObject) to the database by running

rake db:migrate

we get an error saying that the table 'tagged_objects' doesn't exist. It seems like this is because Rails loads the entire environment before it runs migrations. But the environment includes models with acts_as :tagged_object, which expects the tagged_objects table to already exist! So the model requires the table, but creating the table requires the model, which requires the table, and so on.

We got around this issue at first by patching our code to not reference acts_as, running the migrations, then un-patching. But now that we're ramping up our servers that's not a maintainable solution anymore. Does anyone have an idea of how to avoid this problem?

Defining :as => :___able unexpected results?

I have a model page
I have two other models like something and something_else.
These two are set as acts_as :page, :as => :pagable.

For some reason, however, the query is still being built containing as_page_id and as_page_type when I would have expected it to use pagable_id and pagable_type

Am I miss understanding what's suppose to happen?

Why does the parent class need it's own id?

Hi Hassan,

I am wondering why the parent class needs to have an explicit parent_class_id object? Isn't this something that could be automatically derived from the id?

I am fairly new to ROR (and trying to bite off a big bite on the first go), so I apologize if the answer is self-evident.

Thanks,

Dave

methods won't inherit

I followed the example line by line however when I call pen.hello I don't get anything just nil. Any suggestions?

Undefined local variable on rails-3.2.3

Hello,

I.m try to use your gem by following the read me.

class Product < ActiveRecord::Base
attr_accessible :name, :price

acts_as_superclass

validates_presence_of :name, :price

def hello
puts "Hello, My name is '#{name}', my price is $#{price}."
end
end

class Pen < ActiveRecord::Base
attr_accessible :color

acts_as :product, :as => :as_product
end

rails console

p = Pen.new
NameError: undefined local variable or method includeconditionsautosavetrueclass_nameProductasas_productdependentdestroyvalidatefalse' for ActiveRecord::ActsAsModules::ActsAsProduct:Module from /Library/Ruby/Gems/1.8/gems/acts_as_relation-0.1.1/lib/active_record/acts_as_relation.rb:93:inincluded'
from /Library/Ruby/Gems/1.8/gems/acts_as_relation-0.1.1/lib/active_record/acts_as_relation.rb:96:in include' from /Library/Ruby/Gems/1.8/gems/acts_as_relation-0.1.1/lib/active_record/acts_as_relation.rb:96:inacts_as'
from /Library/Ruby/Gems/1.8/gems/acts_as_relation-0.1.1/lib/active_record/acts_as_relation.rb:95:in class_eval' from /Library/Ruby/Gems/1.8/gems/acts_as_relation-0.1.1/lib/active_record/acts_as_relation.rb:95:inacts_as'
from /Users/stefano/RoR/test_acts_as_relation/app/models/pen.rb:4
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:469:in load' from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:469:inload_file'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:639:in new_constants_in' from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:468:inload_file'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:353:in require_or_load' from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:502:inload_missing_constant'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:192:in const_missing' from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:190:ineach'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:190:in `const_missing'
from (irb):1

Have you any idea?

Best regards

ss

NoMethodError: undefined method `acts_as'

I followed the documentation and have following model in my application

class Contest < ActiveRecord::Base
  belongs_to :category
  acts_as_superclass
  attr_accessible :title, :description, :category_id
end

class Quiz < ActiveRecord::Base
  acts_as :contest
end

Contest on console

1.9.3p125 :009 > Contest
 => Contest(id: integer, as_contest_id: integer, as_contest_type: string, title: string, description: text, category_id: integer, created_at: datetime, updated_at: datetime)

When I checked for Quiz on console I get following error

NoMethodError: undefined method `acts_as' for Quiz(id: integer, created_at: datetime, updated_at: datetime):Class
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.1/lib/active_record/dynamic_matchers.rb:50:in `method_missing'
    from /home/saurabh/Desktop/Projects/c2w/app/models/quiz.rb:2:in `<class:Quiz>'
    from /home/saurabh/Desktop/Projects/c2w/app/models/quiz.rb:1:in `<top (required)>'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:469:in `load'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:469:in `block in load_file'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:639:in `new_constants_in'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:468:in `load_file'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:353:in `require_or_load'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:502:in `load_missing_constant'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:192:in `block in const_missing'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:190:in `each'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:190:in `const_missing'
    from (irb):15
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
    from /home/saurabh/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

What did I miss?

Rails 3.0.9 method_missing endless loop?

Given this example:

(assuming Product has a market_id and Pen has a color)

class Product < ActiveRecord::Base
  belongs_to :market  
end

class Pen < ActiveRecord::Base
  acts_as :product

  scope :by_market, lambda{|market_id|
    joins("JOIN products ON products.product_id = pens.id").where(["products.market_id = ?", market_id])
  }
end

if I run this in console:

  Pen.by_market(1).first.color

I get a 'stack level too deep' error.

If I do...

  p = Pen.by_market(1)
  p.color

... it works fine. But obviously we'd want the normal behavior to work as well.

As far as I can tell, it's getting stuck in an endless method_missing loop. Something to do with alias_method_chain's deprecation in Rails 3?

Any help would be much appreciated...

ArgumentError: wrong number of arguments (3 for 2)

I added the acts_as_relation gem to the gem file, and I have a User class where I included the "acts_as_superclass" statement,

the children of the User class are
Admin
Swimmer
Coach

where I added the "acts_as :user" statement
and I added ":as_relation_superclass => true" to my User table DB migration

but this Error appears whenever I try to view the Admin class by writing Admin in the rails console

what am I doing wrong ? sorry for the stupid question but I am a beginner

Finders with hash attributes are not supported

This works:
SubModel.where("attribute = ?", value)

This does not:
SubModel.where(attribute: value)

And I guess that is also related to why this is not supported:
SubModel.find_or_create_by(attribute: value)

It's not crucial, since there are workarounds, but it forces me to write my code in a way I wouldn't normally do. Hashes are simply more elegant.

Build failure when executing "RAILS_ENV=production rake assets:precompile --trace"

When trying to deploy my application I ran into a failure whenever I tried to precompile my assets for production, receiving an error:

** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
rake aborted!
PG::UndefinedTable: ERROR: relation "part_models" does not exist
LINE 5: WHERE a.attrelid = '"part_models"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"part_models"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

I was able to trace the offending code to my model which was calling:

"acts_as :part_model, :as => :partable"

After a bit of troubleshooting I discovered a workaround was to just check if the table exists:

if ActiveRecord::Base.connection.table_exists? 'part_models'
acts_as :part_model, :as => :partable
end

This works but feels a bit hacky.

validation issue?

Not sure why in your example validation is failing on creating a Pen:

Pen.create :name => "Nice Pen", :price => 1.3, :color => "Red"
Pen.where "name = ?", "Some Pen"
pen = Pen.new
pen.valid?      # => false
pen.errors.keys # => [:name, :price]
Pen.first.to_s  # => "Nice Pen $1.3"

A pen object is being created with a name and a price so why is pen.errors showing name/price as validation errors?

Suggested RSpecs...

For those using the RSpec test suite, would be cool if some custom matchers were available:

  1. should act_as_superclass
  2. should act_as_parent
  3. subclass should destroy when parent destroyed
  4. parent should destroy when child subclass destroyed

Extending Devise's User to Roles using acts_as_relation

I left this similar comment on devise's repository, to hopefully see a larger target audience. I'll copy and paste it here to reach another audience while linking to the original.

To make a long story short, I'm attempting to use MTI to create different roles in an application. While this isn't really documented well anywhere, I was hoping to combine the two models that I see as "best practice" (for lack of a better term).

My current issue is when creating or logging into the system using devise, devise seems to query ActiveRecord for specific column names, instead of using ruby attribute calls.

That is, when I try to login to the system, I receive a column not found:

SQLite3::SQLException: no such column: customers.email: SELECT  "customers"."id" AS t0_r0, "customers"."created_at" AS t0_r1, "customers"."updated_at" AS t0_r2, "users"."id" AS t1_r0, "users"."as_user_id" AS t1_r1, "users"."as_user_type" AS t1_r2, "users"."email" AS t1_r3, "users"."encrypted_password" AS t1_r4, "users"."reset_password_token" AS t1_r5, "users"."reset_password_sent_at" AS t1_r6, "users"."remember_created_at" AS t1_r7, "users"."sign_in_count" AS t1_r8, "users"."current_sign_in_at" AS t1_r9, "users"."last_sign_in_at" AS t1_r10, "users"."current_sign_in_ip" AS t1_r11, "users"."last_sign_in_ip" AS t1_r12, "users"."created_at" AS t1_r13, "users"."updated_at" AS t1_r14 FROM "customers" INNER JOIN "users" ON "users"."as_user_id" = "customers"."id" AND "users"."as_user_type" = 'Customer' WHERE "customers"."email" = '[email protected]' LIMIT 1

and when I try to sign up, I receive what appears to be a validation problem:

NoMethodError (undefined method `text?' for nil:NilClass):
  activerecord (3.2.15) lib/active_record/validations/uniqueness.rb:57:in `build_relation'
  activerecord (3.2.15) lib/active_record/validations/uniqueness.rb:25:in `validate_each'
  activemodel (3.2.15) lib/active_model/validator.rb:153:in `block in validate'
  activemodel (3.2.15) lib/active_model/validator.rb:150:in `each'
  activemodel (3.2.15) lib/active_model/validator.rb:150:in `validate'
  activesupport (3.2.15) lib/active_support/callbacks.rb:310:in `_callback_before_55'
  activesupport (3.2.15) lib/active_support/callbacks.rb:429:in `_run__2666856343956316215__validate__3987179287797953709__callbacks'
  activesupport (3.2.15) lib/active_support/callbacks.rb:405:in `__run_callback'
  activesupport (3.2.15) lib/active_support/callbacks.rb:385:in `_run_validate_callbacks'
  activesupport (3.2.15) lib/active_support/callbacks.rb:81:in `run_callbacks'
  activemodel (3.2.15) lib/active_model/validations.rb:228:in `run_validations!'
  activemodel (3.2.15) lib/active_model/validations/callbacks.rb:53:in `block in run_validations!'
  activesupport (3.2.15) lib/active_support/callbacks.rb:425:in `_run__2666856343956316215__validation__3987179287797953709__callbacks'
  activesupport (3.2.15) lib/active_support/callbacks.rb:405:in `__run_callback'
  activesupport (3.2.15) lib/active_support/callbacks.rb:385:in `_run_validation_callbacks'
  activesupport (3.2.15) lib/active_support/callbacks.rb:81:in `run_callbacks'
  activemodel (3.2.15) lib/active_model/validations/callbacks.rb:53:in `run_validations!'
  activemodel (3.2.15) lib/active_model/validations.rb:195:in `valid?'
  activerecord (3.2.15) lib/active_record/validations.rb:69:in `valid?'
  activerecord (3.2.15) lib/active_record/validations.rb:77:in `perform_validations'
  activerecord (3.2.15) lib/active_record/validations.rb:50:in `save'
  activerecord (3.2.15) lib/active_record/attribute_methods/dirty.rb:22:in `save'
  activerecord (3.2.15) lib/active_record/transactions.rb:259:in `block (2 levels) in save'
  activerecord (3.2.15) lib/active_record/transactions.rb:313:in `block in with_transaction_returning_status'
  activerecord (3.2.15) lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
  activerecord (3.2.15) lib/active_record/transactions.rb:208:in `transaction'
  activerecord (3.2.15) lib/active_record/transactions.rb:311:in `with_transaction_returning_status'
  activerecord (3.2.15) lib/active_record/transactions.rb:259:in `block in save'
  activerecord (3.2.15) lib/active_record/transactions.rb:270:in `rollback_active_record_state!'
  activerecord (3.2.15) lib/active_record/transactions.rb:258:in `save'
  devise (3.1.1) app/controllers/devise/registrations_controller.rb:15:in `create'

To me, this looks like devise is relying on activerecord directly instead of the models I've since created. Is there a way to change this functionality or is there a reason it is written this way?

For reference, my routes is devise_for :customers
my user.rb:

class User < ActiveRecord::Base
  #Multi-Table Inheritance. A user can be a Customer, Employee, or an Admin
  acts_as_superclass

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body
end

my customer:

class Customer < ActiveRecord::Base
  acts_as :user

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me

end

(side note: I noticed that you need the devise statements here for the routes to generate properly, and the attr_accessible was added to see if that would permit devise to access the proper variables, to no avail)

and my related schema:

  create_table "customers", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.integer  "as_user_id"
    t.string   "as_user_type"
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0,  :null => false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

Thanks for listening!

Original post: heartcombo/devise#2712

PG::UndefinedColumn, ActiveRecord::StatementInvalid

I have implemented acts_as_relation as follows:

Superclass migration:

class CreateActions < ActiveRecord::Migration
  def change
    create_table :actions, :as_relation_superclass => true do |t|
      t.integer :visit_id
      t.boolean :is_visit_new
      t.timestamps
    end
  end
end

Superclass model:

class Action < ActiveRecord::Base
    acts_as_superclass
        attr_accessible :visit_id, :is_visit_new
end

Subclass model:

class SomeAction < ActiveRecord::Base
    acts_as :action
end

However, when I run any where query, I get a PG::UndefinedColumn error because it seems the SQL generated is wrong.

Example:

SomeAction.where(is_visit_new: false).count

results in:

SELECT COUNT(*) FROM "some_actions" INNER JOIN "actions" ON "actions"."as_action_id" = "some_actions"."id" AND "actions"."as_action_type" = 'SomeAction' WHERE "some_actions"."is_visit_new" = 'f'

Clearly, this would break since the some_actions table doesn't have an is_visit_new column: that has been moved to the actions table. I expected acts_as_relation to generate SQL like this:

SELECT COUNT(*) FROM "some_actions" INNER JOIN "actions" ON "actions"."as_action_id" = "some_actions"."id" AND "actions"."as_action_type" = 'SomeAction' WHERE "actions"."is_visit_new" = 'f'

What am I doing wrong here?

Problem with migration

When I migrate the database but already added the acts_as... I get a database error that the relation does not exist.

PGError: ERROR:  relation "actors" does not exist
WHERE a.attrelid = '"actors"'::regclass

SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"actors"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

where actors is my superclass

As long as I first migrate the database and then add the acts_as... in code it works fine. But In my scenario where I develop on local machine and then deploy it to production I will always have to do it in two steps. First deploy the version with only the migrations and then the version with the code changes.

Also if I would setup a new staging server or new development environment, it will always fail on migrating the database.

Did I miss something in my setup or in the migration to avoid this error?

Controller update_attributes issue: 'ActiveRecord::ReadOnlyRecord'

If I try to update an acts_as_relation model in my controller, I get the following error:

"ActiveRecord::ReadOnlyRecord"

I believe this is something to do with the join on the object's tables (superclass + class tables). I think there should be a '.readonly(false)' in there somewhere, but I'm not sure how to add.

What's the recommended method of updating acts_as_relation objects via forms (e.g. form POST)?

Indexing

Is there any reason the :as_relation_superclass => true option does not add indexes to the product table such as:

index :products, [:as_product_id, :as_product_type]

When looking up a subproduct that acts as a product the following sql is produced

Product Load (53.7ms)  SELECT "products".* FROM "products" WHERE     "products"."as_product_id" = $1 AND "products"."as_product_type" = $2 ORDER BY "products"."id" ASC LIMIT 1  [["as_product_id", 1], ["as_product_type", "Products::Pen"]]

It makes sense to me that the :as_relation_superclass => true should add those indexes, or is that an exercise left to the developer? Maybe make a note of it in the readme?

gem doesn't work when using namespaces

Hi,

I've just tried to write down your sample but using a namespace Stationery. My model is basically same as yours but I added a Catalogue which can have many products and a belongs to catalogue inside the Product model.

class Stationery::Catalogue < ActiveRecord::Base
attr_accessible :name
has_many :products, :dependent =>:destroy
end

class Stationery::Product < ActiveRecord::Base
attr_accessible :name, :price
acts_as_superclass
belongs_to :catalogue
end

class Stationery::Book < ActiveRecord::Base
attr_accessible :title
acts_as :product
end

class Stationery::Pen < ActiveRecord::Base
attr_accessible :color
acts_as :product
end

I get this error:

uninitialized constant ActiveRecord::ActsAsModules::ActsAsProduct::Product (NameError)

I can't figure out exactly what's going on but I'm pretty sure is something about the namespaces, in the error the namespace is missing so I thing that could be the reason, when I'm not using namespaces everything works fine.

BR!

Associations don't inherit

Followed the guide in the readme, and have Pen inheriting from Product fine. However, your readme says that Pen should inherit associations. I have a User model with a has_many :products relationship, however I do not get a User.pens method?

attr_accessible in every model

Hi! First of all thanks for your plugin, it works great and it makes MTI very easy to implement for a Rails newbie like me.
The only issue I've found is that have to write the attr_accessible in every class, instead of only doing it in my acts_as_superclass class... is this correct or am I doing something wrong?

validates_uniqueness_of() and exists?() don't work

From what I can tell, validates_uniqueness_of calls exists?(), which isn't going to work in your current code, I believe. If you, say, try to do SubThing.exists?(:name => 'foo') ... it's going to generate SQL query with "WHERE sub_things.name = 'foo'" which will then throw a StatementInvalid error because there's no 'name' column on the sub_things table.

I believe it needs to somehow traverse back up in the case of exists?() and see if the supplied attribs work for the parent object. Unfortunately, I've tried to hack that in and couldn't get something that worked reliably. Not sure why...

has_many through is not working

Hi!
I don't know if this is a bur or not, but I have the following models:

class Client < ActiveRecord::Base
    acts_as_superclass
    belongs_to :company
    ...
end

class Provider < ActiveRecord::Base
    acts_as :client
    ...
end

class Company < ActiveRecord::Base
    has_many :clients
    has_many :providers, through: :clients
    ...
end

If I try to get the providers of a Company, I get the following error:

ctiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :provider or :providers in model Client. Try 'has_many :providers, :through => :clients, :source => <name>'. Is it one of :as_client, :contact_people, :addresses, or :company?

Is it a bug or am I creating the relation in a wrong way?
Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.