Below I have outlined the structure of a polymorphic association.
In VacationsController I put some comments inline describing my current issue. However, I wanted to post this to see if my whole approach here is a little off. You can see in business_vacations_controller and staff_vacations_controller that I've had to make 'getters' for the model and controller so that I can access them from within vacations_model so I know which type of object I'm dealing with. Although it works, it's starting to feel a little questionable.
Is there a better 'best practice' for what I'm trying to accomplish?
models
vacation.rb
class Vacation < ActiveRecord::Base
belongs_to :vacationable, :polymorphic => true
end
business.rb
class Business < ActiveRecord::Base
has_many :vacations, :as => :vacationable
end
staff.rb
class Staff < ActiveRecord::Base
has_many :vacations, :as => :vacationable
end
business_vacation.rb
class BusinessVacation < Vacation
end
staff_vacation.rb
class StaffVacation < Vacation
end
controllers
business_vacations_controller.rb
class BusinessVacationsController < VacationsController
private
def controller_str
"business_schedules"
end
def my_model
BusinessVacation
end
def my_model_str
"business_vacation"
end
end
staff_vacations_controller.rb
class StaffVacationsController < VacationsController
private
def controller_str
"staff_schedules"
end
def my_model
StaffVacation
end
def my_model_str
"staff_vacation"
end
end
vacations_controller.rb
class VacationsController < ApplicationController
def create
# Build the vacation object with either an instance of BusinessVacation or StaffVacation
vacation = #class.new(params[my_model_str])
# Now here's the current issue -- I want to save the object on the association. So if it's a 'BusinessVacation' object I want to save something like:
business = Business.find(vacation.vacationable_id)
business.vacations.build
business.save
# But if it's a 'StaffVacation' object I want to save something like:
staff = Staff.find(vacation.vacationable_id)
staff.vacations.build
staff.save
# I could do an 'if' statement, but I don't really like that idea. Is there a better way?
respond_to do |format|
format.html { redirect_to :controller => controller_str, :action => "index", :id => vacation.vacationable_id }
end
end
private
def select_class
#class = Kernel.const_get(params[:class])
end
end
It feels like a lot of hoops to jump through in the VacationsController to make it aware of the context. Is there a reason that the StaffVacationsController and BusinessVacationsController couldn't each have a #create action and the views would submit to whichever is appropriate? These actions would already know the model context and be able to redirect to the appropriate url afterward.
Related
I'll ask my question first:
Will this code logically work and it is the right thing to do (best practices perspective)? First off, it looks strange having a user being passed to a static subscription method
User and magazine have a many to many relationship through subscriptions (defined below). Also you can see, I've used through joins instead of the has and belongs to many so that we can define a subscription model.
after creating a user they need to have default subscriptions. Following the single responsibility principle, I don't think a user should have to know what default magazines to subscribe to. So how, after a user has been created can I create default subscriptions. The user.likes_sports? user.likes_music? should define which subscriptions methods we want.
Am I on the right track? I don't have anyone to review my code, any code suggestions highly appreciated.
class User < ActiveRecord::Base
after_create create_default_subscriptions
has_many :magazines, :through => :subscriptions
has_many :subscriptions
def create_default_subscriptions
if self.likes_sports?
Subscription.create_sports_subscription(self)
end
end
end
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :magazine
#status field defined in migration
def self.create_sports_subscription(user)
Magazine.where("category = 'sports'").find_each do |magazine|
user.subscriptions << Subscription.create(:user => user, :magazine => magazine, :status=>"not delivered")
end
end
.
.
end
class Magazine < ActiveRecord::Base
has_many :users, :through => :subscriptions
has_many :subscriptions
end
The code is too coupled in my view. This can get out of hand really easily.
The right way to do this in my view would be to create a new service/form that takes care of creating the user for you
class UserCreationService
def perform
begin
create_user
# we should change this to only rescue exceptions like: ActiveRecord::RecordInvalid or so.
rescue => e
false
end
end
private
def create_user
user = nil
# wrapping all in a transaction makes the code faster
# if any of the steps fail, the whole user creation will fail
User.transaction do
user = User.create
create_subscriptions!(user)
end
user
end
def create_subscriptions!(user)
# your logic here
end
end
Then call the code in your controller like so:
def create
#user = UserCreationService.new.perform
if #user
redirect_to root_path, notice: "success"
else
redirect_to root_path, notice: "erererererooooor"
end
end
In Ruby on Rails I have a user models and a jobs model joined through a different model called applicants. I have a button for the users when they want to "remove their application for this job" but I don't know how to remove the specific user, and for that matter I don't know if I'm doing a good job at adding them either (I know atleast it works).
user.rb
class User < ActiveRecord::Base
...
has_many :applicants
has_many:jobs, through: :applicants
end
job.rb
class Job < ActiveRecord::Base
...
has_many :applicants
has_many:users, through: :applicants
end
applicant.rb
class Applicant < ActiveRecord::Base
belongs_to :job
belongs_to :user
end
when someone applies for a job my jobs controller is called:
class JobsController < ApplicationController
...
def addapply
#job = Job.find(params[:id])
applicant = Applicant.find_or_initialize_by(job_id: #job.id)
applicant.update(user_id: current_user.id)
redirect_to #job
end
...
end
Does that .update indicate that whatever is there will be replaced? I'm not sure if I'm doing that right.
When someone wants to remove their application I want it to go to my jobs controller again but I'm not sure what def to make, maybe something like this?
def removeapply
#job = Job.find(params[:id])
applicant = Applicant.find_or_initialize_by(job_id: #job.id)
applicant.update(user_id: current_user.id).destroy
redirect_to #job
end
does it ave to sort through the list of user_ids save them all to an array but the one I want to remove, delete the table then put them all back in? I'm unsure how this has_many works, let alone has_many :through sorry for the ignorance!
thanks!
Let's assume the user will want to remove their own application. You can do something like this:
class UsersController < ApplicationController
def show
#applicants = current_user.applicants # or #user.find(params[:id]), whatever you prefer
end
end
class ApplicantsController < ApplicationController
def destroy
current_user.applications.find(params[:id]).destroy
redirect_to :back # or whereever
end
end
And in your view:
- #applicants.each do |applicant|
= form_for applicant, method: :delete do |f|
= f.submit
Don't forget to set a route:
resources :applicants, only: :destroy
Some observations, I would probably name the association application instead of applicant. So has_many :applications, class_name: 'Applicant'.
I have one model but two different forms ,one form i am saving through create action and another one through student_create action.I want to validate a field in student_create action form and leave other one free.How do i do it?Any help will be appreciated
class BookController < ApplicationController
def create
if #book.save
redirect_to #book #eliminated some of the code for simplicity
end
end
def student_create
if #book.save #eliminated some of the code for simplicity
redirect_to #book
end
end
I have tried this but it didnt work
class Book < ActiveRecord::Base
validates_presence_of :town ,:if=>:student?
def student?
:action=="student_create"
end
end
Also this didnt work
class Book < ActiveRecord::Base
validates_presence_of :town ,:on=>:student_create
end
In the one that should not be validated you do this:
#object = Model.new(params[:xyz])
respond_to do |format|
if #object.save(:validate => false)
#do stuff here
else
#do stuff here
end
end
the save(:validate => false) will skipp the validation.
I was able to acomplish it what i wanted to do by giving it an option :allow_nil=>true
Sounds like you have two types of books. not sure what your domain logic is but the normal flow I would do nothing.
class Book < ActiveRecord::Base
end
Then for the path you want an extra validation you could do this:
class SpecialBook < Book
validates :town, :presence => true
end
If this is the case you might want to consider Single Table Inheritance.
In another case you might want to save the student_id on the book.
Then
class Book < ActiveRecord::Base
validate :validate_town
private
def validate_town
if student_id
self.errors.add(:town, "This book is evil, it needs a town.") if town.blank?
end
end
end
So, I've read in some book about tip "Use model association", which encourages developers to use build methods instead of putting ids via setters.
Assume you have multiple has_many relationships in your model. What's best practise for creating model then ?
For example, let's say you have models Article, User and Group.
class Article < ActiveRecord::Base
belongs_to :user
belongs_to :subdomain
end
class User < ActiveRecord::Base
has_many :articles
end
class Subdomain < ActiveRecord::Base
has_many :articles
end
and ArticlesController:
class ArticlesController < ApplicationController
def create
# let's say we have methods current_user which returns current user and current_subdomain which gets current subdomain
# so, what I need here is a way to set subdomain_id to current_subdomain.id and user_id to current_user.id
#article = current_user.articles.build(params[:article])
#article.subdomain_id = current_subdomain.id
# or Dogbert's suggestion
#article.subdomain = current_subdomain
#article.save
end
end
Is there a cleaner way ?
Thanks!
This should be a little cleaner.
#article.subdomain = current_subdomain
The only thing I can think of is merging the subdomain with params:
#article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))
The Getting Started Rails Guide kind of glosses over this part since it doesn't implement the "new" action of the Comments controller. In my application, I have a book model that has many chapters:
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
In my routes file:
resources :books do
resources :chapters
end
Now I want to implement the "new" action of the Chapters controller:
class ChaptersController < ApplicationController
respond_to :html, :xml, :json
# /books/1/chapters/new
def new
#chapter = # this is where I'm stuck
respond_with(#chapter)
end
What is the right way to do this? Also, What should the view script (form) look like?
First you have to find the respective book in your chapters controller to build a chapter for him. You can do your actions like this:
class ChaptersController < ApplicationController
respond_to :html, :xml, :json
# /books/1/chapters/new
def new
#book = Book.find(params[:book_id])
#chapter = #book.chapters.build
respond_with(#chapter)
end
def create
#book = Book.find(params[:book_id])
#chapter = #book.chapters.build(params[:chapter])
if #chapter.save
...
end
end
end
In your form, new.html.erb
form_for(#chapter, :url=>book_chapters_path(#book)) do
.....rest is the same...
or you can try a shorthand
form_for([#book,#chapter]) do
...same...
Try #chapter = #book.build_chapter. When you call #book.chapter, it's nil. You can't do nil.new.
EDIT: I just realized that book most likely has_many chapters... the above is for has_one. You should use #chapter = #book.chapters.build. The chapters "empty array" is actually a special object that responds to build for adding new associations.
Perhaps unrelated, but from this question's title you might arrive here looking for how to do something slightly different.
Lets say you want to do Book.new(name: 'FooBar', author: 'SO') and you want to split some metadata into a separate model, called readable_config which is polymorphic and stores name and author for multiple models.
How do you accept Book.new(name: 'FooBar', author: 'SO') to build the Book model and also the readable_config model (which I would, perhaps mistakenly, call a 'nested resource')
This can be done as so:
class Book < ActiveRecord::Base
has_one :readable_config, dependent: :destroy, autosave: true, validate: true
delegate: :name, :name=, :author, :author=, :to => :readable_config
def readable_config
super ? super : build_readable_config
end
end