RailsActive Record and Nested Resources - ruby-on-rails

I would like for click action on a button to result in the addition of a resource to a join table. There are several ways to do this in the console but I can't for the life of me figure out how to implement this outside the console.
Here is an example that mimics my current model:
class Student < ActiveRecord::Base
has_many :reports
has_many :schools, through: :reports
end
class School < ActiveRecord::Base
has_many :reports
has_many :students, through: :reports
accepts_nested_attributes_for :reports
end
class Report < ActiveRecord::Base
belongs_to :student
belongs_to :school
accepts_nested_attributes_for :student
accepts_nested_attributes_for :school
validates :student_id, presence: true
validates :school_id, presence: true
end
This method returns all the report cards that belong to a student (student already exists in
my database):
#student.reports
This method returns all the schools that a student has attended:
#student.schools
I can add/associate an existing school to a student by doing this:
#school = School.find(params[:id])
if student.present?
#student = Student.find(params[:id])
#student.schools << #school
Please note that the association of a single report to many students is intentional. My question now is how do I enable a student to add a school to their report simply by clicking on a particualr school? My reports table (which basically is a join table) should be automatically updated as soon as this click_action takes place/happens (that is a new row that associates that particular student_id with that particular school id should be created).
Been trying to figure it out but not making progress for some reason. Thank you in advance!

Well, to start with, in your view you should have a javascript/DOM event for each school:
onclick(window.location.href = "<%= path_to_add_school_to_students(student,school) %>")
So there you have your one click.
In your controller
student=Student.find(params[:student])
if student.schools.find(params[:school]).nil? # if school not already assigned
student.reports.create(:school_id => params[:school])
end

Related

has_one association with chaining include

We have a Company, CompanyUser, User and Rating model defined like this:
Company model
class Company < ActiveRecord::Base
has_many :company_users
has_many :users, through: :company_users
has_one :company_owner, where(is_owner: true), class_name: 'CompanyUser', foreign_key: :user_id
has_one :owner, through: :company_owner
end
There is an is_owner flag in the company_users table to identify the owner of the company.
CompanyUser model
class CompanyUser < ActiveRecord::Base
belongs_to :company
belongs_to :user
belongs_to :owner, class_name: 'User', foreign_key: :user_id
end
User model
class User < ActiveRecord::Base
has_many :company_users
has_many :companies, through: :company_users
has_many :ratings
end
Rating model
class Rating
belongs_to :user
belongs_to :job
end
I am able to find the owner of a company, by the following code:
#owner = #company.owner
I need to get the ratings and the jobs of the owner along with the owner. I can do this
#owner = #company.owner
#ratings = #owner.ratings.includes(:job)
But we have already used #owner.ratings at many places in the view, and it is difficult to change all the references in the views as it is a pretty big view spanning in several partials. I tried the following to get the ratings along with the owner
#owner = #company.owner.includes(:ratings => :job)
But this gives me error as #company.owner seems to give a User object and it does not seem to support chaining.
Is there a way I can get the included associations (ratings and job) inside the #owner object?
You should be able to do this with:
#owner = Company.where(id: #company.id).includes(owner: {ratings: :job}).owner
However this is not very clean. Much better would be to actually change #company variable:
#company = Company.includes(owner: {ratings: :job}).find(params[:company_id]) # or params id or any other call you're currently using to get the company.
Company built that way will already have everything included, so:
#owner = #company.owner
will pass a model with preloaded associations.

Rails ActiveRecord model association

I have a User model and a product model.
User has_many :products, :dependent => :destroy
Product belongs_to :user, :foreign_key => "user_id", touch: true
I want to create a wishlist for every user.
So i have to create a wishlist model with proper association.
But i don't know how to start.
I presume that the wishlist model contain an id, user_id and product_id field
Do i have to use has_many through association or a has_and_belongs_to_many ?
I also want that if a user is destroyed to destroy his wishlist.
What is the best way to do?
Many thanks!
As #JZ11 pointed out, you shouldn't be linking a Product directly to a User (unless a User actually 'owns' a product for some reason). However, what was missed is the model that makes up a Wishlist item:
class User < ActiveRecord::Base
has_many :wishlists # or has_one, depending on how many lists a User can have...
end
class Product < ActiveRecord::Base
has_many :wishlist_items
end
class Wishlist < ActiveRecord::Base
belongs_to :user
has_many :wishlist_items
has_many :products, :through => :wishlist_items
end
class WishlistItem < ActiveRecord::Base
belongs_to :product
belongs_to :wishlist
end
Naturally, you should be adding :dependent => :destroy where necessary.
You don't need the has_many :products relationship on User.
I don't think it makes sense for User and Product to be linked outside of a Wishlist.
class Wishlist < ActiveRecord::Base
has_many :products
belongs_to :user
end
class User < ActiveRecord::Base
has_one :wishlist, dependent: :destroy
end
class Product < ActiveRecord::Base
belongs_to :wishlist
end
To create your join table, do:
rails g migration create_products_users_table
Once you've done that, you need to add some code, below, to create the fields in the join table. Notice the :id => false, because you do not need an id in the join table:
class CreateProductsUsersTable < ActiveRecord::Migration
def change
create_table :products_users, :id => false do |t|
t.references :product
t.references :user
end
add_index :products_users, [:product_id, :user_id]
add_index :products_users, :user_id
end
end
The code above also creates some indexes and ensures that you don't have duplicates even at the database level.
Your models would then have to look like this:
class Product < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :products
end
When you destroy a user correctly, like user.destroy and not just delete it (there is a difference), then the related rows in the join table will be deleted as well. This is built in to ActiveRecord.
Notice though, that doing this will not really let you use the join table. It will accept code like user.products = [product1, product2] etc, and other goodies, but no real use of a wish list.
If you do want to use a wish list, you will have to create and use the middle join table differently, using has_many :through (I didn't check PinnyM's answer but that might be the way to do it).

Rails admin hide belongs_to field in has_many nested form

I have two Models
class Entity < ActiveRecord::Base
# Associations
has_many :contacts
accepts_nested_attributes_for :contacts, :allow_destroy => true
end
class Contact < ActiveRecord::Base
# Associations
belongs_to :entity
end
Now in rails admin I am getting below options.
Add new Contact Form
Add new Entity Form
I need to hide Entity field in contact form , while adding new entity.
Any help will be useful.
You can automatically hide the fields using inverse_of like this
class Entity < ActiveRecord::Base
# Associations
has_many :contacts, inverse_of: :entity
accepts_nested_attributes_for :contacts, allow_destroy: true
end
class Contact < ActiveRecord::Base
# Associations
belongs_to :entity, inverse_of: :contacts
end
If you set the :inverse_of option on your relations, RailsAdmin will
automatically populate the inverse relationship in the modal creation
window. (link next to :belongs_to and :has_many multi-select widgets)
Source: https://github.com/sferik/rails_admin/wiki/Associations-basics
Let me know how it went
For the sake of completness and because i had this problem too and solved it, if you want to you can configure a model when it is used inside a nested form just like you do with edit, update, create and nested
class Contact < ActiveRecord::Base
# Associations
belongs_to :entity
rails_admin do
nested do
configure :entity do
hide
end
end
end
end
Visit the official wiki for more info

ActiveRecord won't build the right class using STI

I'm using single table inheritance in my application and running into problems building inherited users from an ancestor. For instance, with the following setup:
class School < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
attr_accessible :type #etc...
belongs_to :school
end
Class Instructor < User
attr_accessible :terms_of_service
validates :terms_of_service, :acceptance => true
end
Class Student < User
end
How can I build either a instructor or student record from an instance of School? Attempting something like School.first.instructors.build(....) gives me a new User instance only and I won't have access to instructor specific fields such as terms_of_service causing errors later down the rode when generating instructor-specific forms, building from console will give me an mass-assignment error (as it's trying to create a User record rather than an Instructor record as specified). I gave the example of School, but there are a few other associations that I would like to inherit from the User table so I don't have to repeat code or fields in the database. Am I having this problem because associations can not be shared in an STI setup?
You should specify instructors explicitly
class School < ActiveRecord::Base
has_many :users
has_many :instructors,:class_name => 'Instructor', :foreign_key => 'user_id'
end
And what else:
class School < ActiveRecord::Base
has_many :users
has_many :instructors
end
class Instructor < User
attr_accessible :terms_of_service # let it be at the first place. :)
validates :terms_of_service, :acceptance => true
end
OK it seems part of the problem stemmed from having the old users association inside of my School model. Removing that and adding the associations for students and instructors individually worked.
Updated School.rb:
class School < ActiveRecord::Base
#removed:
#has_many :users this line was causing problems
#added
has_many :instructors
has_many :students
end

How to delete nested objects in Rails3?

How can I delete nested objects in a form? I found out that I need to add :allow_destroy in the parent model at the accepts_nested_attributes_for directive.
Further, I want to restrict the deletion. A nested object only should be deleted, if the parent object is the only one that retains the association.
Example:
class Internship < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company, allow_destroy => true
end
class Company < ActiveRecord::Base
has_many :internships
end
Explanation: A company can host many internships. Therefore, I do not want to delete the company record as long as there is at least one other internship associated with it.
You could use dependent => :destroy
class Internship < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company, allow_destroy => true
end
class Company < ActiveRecord::Base
has_many :internships, :dependent => :destroy
end
If you return false in a before_destroy filter, then the destroy action will be blocked. So we can check to see if there are any internships associated to the company, and block it if so. This is done in the company model.
class Company < ActiveRecord::Base
has_many :internships
before_destroy :ensure_no_internships
private
def ensure_no_internships
return false if self.internships.count > 0
end
end

Resources