I have these models:
class Item < ActiveRecord::Base
has_many :item_categoryships
has_many :categories, class_name: 'ItemCategoryship', foreign_key: 'category_id', :through => :item_categoryships
belongs_to :user
validates :title, presence: true
end
class Category < ActiveRecord::Base
has_many :item_categoryships
has_many :items, :through => :item_categoryships
belongs_to :user
validates :name, presence: true
end
class ItemCategoryship < ActiveRecord::Base
belongs_to :item
belongs_to :category
validates :item_id, presence: true
validates :category_id, presence: true
end
class User < ActiveRecord::Base
has_many :items
has_many :categories, class_name: 'Category'
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :async
end
But I found when I call item.categories will get a empty array !!! I have checked database, there is a record here.
When I test in the rails console, I didn't get any record back, just saw 'ActiveRecord::Associations::CollectionProxy []'.
What is this? I am using Rails 4.0.2.
Thanks you all.
ActiveRecord::Associations::CollectionProxy is ActiveRecord class for collection associations. Now, your code should work if you change line in Item class describing categories association to:
has_many :categories, through: :item_categoryships
Related
I want to get the username of comment author like this
comment.commenter
models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :commenter
belongs_to :commentable, polymorphic: true
end
models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username, presence: true, uniqueness: true
has_many :comments, as: :commenter
end
When i try to create Comment directly to db using this line of code:
Comment.create(commentable_type: 'Pokemon', commentable_id: 1, content: 'great', commenter: 1)
It throws this error
NameError: uninitialized constant Comment::Commenter
from /var/lib/gems/2.3.0/gems/activerecord-4.2.6/lib/active_record/inheritance.rb:158:in `compute_type'
I've read somewhere as: is used only for polymorphic assocciations so that might be the case of my error but couldn't figure out how to get around this problem
I don't think as: is what you are looking for. I think your issue is similar to the issue in belongs_to with :class_name option fails
Try
# user.rb
has_many :comments, foreign_key: "commenter_id"
# comment.rb
belongs_to :commenter, class_name: "User", foreign_key: "commenter_id"
Let's explain a bit before going to the solution, if you write this code:
belongs_to :commentable, polymorphic: true
It implicitly means:
belongs_to :commentable, foreign_key: 'commentable_id', foreign_type: 'commentable_type', polymorphic: true
And
has_many :comments, as: :commentable
It specifies the syntax of polymorphic, that also means the foreign_key is commentable_id and foreign_type is commentable_type so if you want to change commentable to commenter, it is possible, you can do like this:
class Comment < ActiveRecord::Base
belongs_to :commenter, foreign_key: 'commentable_id', foreign_type: 'commentable_type', polymorphic: true
end
class User < ActiveRecord::Base
has_many :comments, as: commentable
end
That 's it!
For detail, please go through has_many and belongs_to documentation
I have three models and here they are when I try to create a has_many. I basically want my users (using devise) to have many categories. And categories to have many users.
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable
has_many :user_categories
has_many :categories, through: :user_categories
acts_as_messageable
def mailboxer_email(object)
email
end
end
userCategory.rb
class UserCategory < ActiveRecord::Base
belongs_to :user
belongs_to :category
accepts_nested_attributes_for :categories
end
Category.rb
class Category < ActiveRecord::Base
has_many :user_categories
has_many :user, through: :user_categories
validates :name, presence: true, length: {minimum: 3, maximum: 25}
validates_uniqueness_of :name
end
when I run category.users << user I get this error:
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_categories in model Category
I can't say for sure what the problem could be, but a few things I could point out:
UserCategory's accepts_nested_attributes_for, does that mean the you want to be able to dynamically create categories?
Category has_many :users, through: :user_categories, not user
You need to follow the Rails file naming conventions, user.rb, user_category.rb and category.rb
These may not be the problem/solution, but I believe they're in the way of resolving the problem.
I recently downloaded and installed Devise for Rails 4. I used it on the model "actors"; which have a subset model called "employee"
For the class "Actor"
class Actor < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
include UUIDHelper
has_one :access, autosave: true
has_one :employee, autosave: true
has_many :contact_detail, autosave: true
has_many :file_set
has_many :link_set
mount_uploader :logo, AvatarUploader
validates :name, uniqueness: true
validates_presence_of :name
validates_length_of :description, maximum: 256
def actor_name
actor.name
end
validates :logo,
:file_size => {
:maximum => 25.megabytes.to_i
}
end
For the class "Employee"
class Employee < ActiveRecord::Base
include UUIDHelper
belongs_to :actor
has_one :status
has_many :restdays
has_one :regular_work_period
validates_presence_of :actor
end
I previously had this relation unto a view:
<td><%= employee.actor.name %></td>
Now it spews out an error:
undefined method `name' for nil:NilClass
What did I do wrong? Did Devise do something?
That error indicates this employee object doesn't have actor. employee.actor outputs nil.
Just check your employee object is loaded correctly. It is not a Devise problem.
Here is my join model:
class CompanyUser < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
My User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
ROLES = %w[admin requestor requestor_limited shipping_vendor].freeze
attr_accessor :temp_password
has_many :companies_users
...
end
If I run this in the console:
u = User.first
u.companies
This is the error I am getting:
NameError: uninitialized constant User::CompaniesUser
has_many through relationships should be like this:
In app/models/company.rb file,
has_many :company_users
has_many :users, :through => :company_users
In app/models/user.rb file,
has_many :company_users
has_many :companies, :through => :company_users
In app/models/company_user.rb file,
belongs_to :company
belongs_to :user
If you want to delete the dependent records in company_users table when deleting companies/users,
Add, , :dependent => :destroy at the end of has_many relations in Company and User model.
Hope this helps you..
Thanks.!!
it must be
has_many :company_users
"CompanyUser".tableize => "company_users"
The model shall be either:
class CompaniesUser < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
Or has_many declaration sheel be defined explicitly as:
class User < ActiveRecord::Base
has_many :company_users
end
I am using devise and I want create a polymorphic relationship, I added the columns to table users 'usersable_type' and 'usersable_id'
This is my code
Model >> User
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
# attr_accessible :title, :body
attr_accessible :email, :password, :password_confirmation, :remember_me
#usarsable
belongs_to :usersable, :polymorphic => true, :autosave => true, :dependent => :destroy
accepts_nested_attributes_for :usersable
end
Model >> Medic
class Medic < ActiveRecord::Base
attr_accessible :license_number, :specialty
has_one :user, as: :usersable, dependent: :destroy
has_and_belongs_to_many :patients
end
Model >> Patient
class Patient < ActiveRecord::Base
belongs_to :socialsecurity
attr_accessible :birthday, :blood_type
has_one :user, as: :usersable, dependent: :destroy
has_many :contacts
has_and_belongs_to_many :medics
end
Override Devise Controller
class RegistrationsController < Devise::RegistrationsController
def new
super
#user.build_usersable # I had problem in this line
end
def create
end
def update
super
end
end
Those are all the models I have for the moment, but I still have the same problem, I dont know how create and save the polymorphic object.
The error still is the same
ERROR: undefined method `build_usersable' for "<#User:"
Is anyone can help me I would be grateful
Regards and thanks in advance
Juli.
Based on the conversation in the comments this is the kind of scheme i think you need.
I am going to use the concept of Aspect, that is a user can have many aspects, the aspect might be a medic, a content detail etc; an Aspect can have only one user.
First you need a UserAspect model which has a user_id and a aspect_type and aspect_id
class UserAspect < ActiveRecord::Base
belongs_to :user
belongs_to :aspect, :polymorphic => true
end
Now your user model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
# attr_accessible :title, :body
attr_accessible :email, :password, :password_confirmation, :remember_me
#aspects
has_many :user_aspects
has_many :aspects, :through => :user_aspects
end
And now your medic
class Medic < ActiveRecord::Base
attr_accessible :license_number, :specialty
has_one :user_aspect, as: :aspect, dependent: :destroy
has_one :user, :through => :user_aspect
end
Now you can do things like
user.aspects
medic.user
etc