I have the following situation:
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
after_create :create_profile
after_create :programstart
has_one :profile, dependent: :destroy
has_many :weights, dependent: :destroy
has_many :programstarts, dependent: :destroy
has_many :user_nutrients, dependent: :destroy
has_many :nutrients, through: :user_nutrients, dependent: :destroy
private
def programstart
Programstart.create(:user_id => id)
end
end
nutrient.rb
class Nutrient < ActiveRecord::Base
validates :name, uniqueness: true
has_many :user_nutrients
has_many :users, through: :user_nutrients
end
user_nutrient.rb
class UserNutrient < ActiveRecord::Base
belongs_to :user
belongs_to :nutrient
end
For profile, weights and programstarts the dependent: :destroy works. All the associated database entries are removed when I delete the user. However, for user_nutrients the dependent: :destroy is not working. After deleting the user these entries are stil there.
What am I missing here?
According to this post -
http://makandracards.com/makandra/32175-don-t-forget-automatically-remove-join-records-on-has_many-through-associations
you should do the following:
has_many :user_nutrients
has_many :nutrients, through: :user_nutrients, dependent: :destroy
and in nutrient.rb
has_many :user_nutrients
has_many :users, through: :user_nutrients, dependent: :destroy
Related
I'm working on rails project, and i want to create some user rating system, it means that each user has the ability to leave feedback on another user, and the user can also change the score he left behind, so the question is how to implement these associations in rails correctly ?
I already have my User model here it is
class User < ApplicationRecord
mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
enum role: [ :user, :admin ]
end
Well, As I have understood your problem this is ONE-TO-MANY association.
User -many-> Ratings
class User < ApplicationRecord
mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings, dependent: :destroy
enum role: [ :user, :admin ]
end
Now Create a Rating model which will have its attribute rating_point, user_id and creator_id where user_id is on which rating is given and creator_id is the User who is giving the rating to the user.
class Rating < ApplicationRecord
belongs_to: user
end
Try this It will solve your problem. If not please let me know.
All, i am currently learning Rails and proceeding with a project and i am running into an issue.I am unable to show the image of the user who the post belongs to.
When i go to the home page, i should see the post of the users who you are following ... and unfortunately i am not sure how i can show the image of user who the post belongs to.... i can show their post but not sure how i show their image. I must say i am using paperclip gem.
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
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage/.*\Z/
has_many :followeds, through: :relationships
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id"
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many:avatar, dependent: :destroy
has_many :posts, dependent: :destroy # remove a user's posts if his account is deleted.
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
def avatar_url
avatar.url(:medium)
end
# helper methods
# follow another user
def follow(other)
active_relationships.create(followed_id: other.id)
end
# unfollow a user
def unfollow(other)
active_relationships.find_by(followed_id: other.id).destroy
end
# is following a user?
def following?(other)
following.include?(other)
end
end
i can get the current user image, but if i log into my account, and i am following someone, i want to see their image not mine for their associated post..
<%=image_tag(current_user.avatar.url, class: "img-circle img-responsive img-raised", :size => "100x100") %>
Your post has to have belongs_to :user and user_id in database, then you can do it like this:
#posts.each do |post|
<%=image_tag(post.user.avatar.url, class: "img-circle img-responsive img-raised", :size => "100x100") %>
end
But i see you have has_many :avatar it could be mistake in you code posted here, if not you have to first select which avatar_url you want to use.
In ActiveAdmin, when I want to delete a user I have the following error :
ActiveRecord::InvalidForeignKey in Admin::UsersController#destroy
PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_b080fb4855" on table "notifications" DETAIL: Key (id)=(15) is still referenced from table "notifications". : DELETE FROM "users" WHERE "users"."id" = $1
I already have has_many :notifications, dependent: :destroy in my User model so I don't understand the error.
Notification model:
class Notification < ActiveRecord::Base
before_validation :check_modeles
validates :message, presence: true
validates :modele, presence: true
validates :user_id, presence: true
validates :contact_id, presence: true
validates_associated :user
belongs_to :user
belongs_to :contact, :class_name => "User", :foreign_key => "contact_id"
User model :
class User < ActiveRecord::Base
before_validation :check_genres
before_validation :set_image
before_validation :init_attrs
before_create :set_name
before_create :create_mangopay
after_create :set_centres_interets
after_create :set_preferences_musicales
after_create :check_on_create
after_update :check_on_update
before_update :create_mangopay_bank_account
before_destroy :remove_contact_notifications
acts_as_mappable :default_units => :kms,
:lat_column_name => :last_lat,
:lng_column_name => :last_lng
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
has_one :fil, dependent: :destroy
has_one :preferences_voyage, dependent: :destroy
has_one :verification, dependent: :destroy
has_many :badges, dependent: :destroy
has_many :favoris , dependent: :destroy
has_many :centres_interets, dependent: :destroy
has_many :preferences_musicales, dependent: :destroy
has_many :recommandations, dependent: :destroy
has_many :reputations, dependent: :destroy
has_many :reservations, dependent: :destroy
has_many :routes, dependent: :destroy
has_many :trajets_reguliers, dependent: :destroy
has_many :vehicules, dependent: :destroy
has_many :contact_notifications, foreign_key: 'contact_id', class_name: 'Notification', dependent: :destroy
has_many :notifications, dependent: :destroy
has_many :recherches, dependent: :destroy
has_many :blocages, dependent: :destroy
has_many :messageries, dependent: :destroy
has_many :messages, dependent: :destroy
validates :date_naissance, presence: true
validates :first_name, presence: true
validates :last_name, presence: true
Maybe the has_many :notifications, dependent: :destroy only affect the user and not the contact? If so, how do i fix it?
Ok, maybe your best bet is to just remove the foreign key constraints.
Create a migration with the following lines
remove_foreign_key :notifications, :users
remove_foreign_key :notifications, column: :contact_id
Rails doesn't require the foreign key constraints, and they're clearly not helping here.
You can also remove it by name...
remove_foreign_key :notifications, name: :fk_rails_b080fb4855
In your PostgreSQL database table notifications you have two different foreign keys that relate to users the user_id and the contact_id and the dependent: destroy only relates to the user_id.
Add another has_many to your User model to cover the second association
has_many :contact_notifications, foreign_key: 'contact_id', class_name: 'Notification', dependent: :destroy
Also, ensure that you're using the destroy method when you're deleting a user
#user.delete # will NOT run callbacks
#user.destroy # will run callbacks including destroying dependent records
To be sure that the issue is related to contact_id you can try removing those records with a manual process
class User
before_destroy :remove_contact_notifications
def remove_contact_notifications
Notification.where(contact_id: id).destroy_all
Notification.where(user_id: id).destroy_all
end
end
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 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