Rails 3: How to create a new nested resource? - ruby-on-rails

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

Related

Adding Posts To A Collection with Join Models

I'm trying to add a 'Collections' model to group Posts so that any user can add any Post they like to any Collection they've created. The Posts will have already been created by a different user. We are just letting other users group these posts in their own Collections. Basically like bookmarking.
What is the cleanest, and most Rails-ey-way of doing this?
I've created the model and run through the migration and what not. Also I've already created proper views for Collection.
rails g model Collection title:string user_id:integer
collections_controller.rb
class CollectionsController < ApplicationController
def index
#collections = current_user.collections.all
end
def show
#collection = Collection.all
end
def new
#collection = Collection.new
end
def create
#collection = current_user.collections.build(collection_params)
if #collection.save
redirect_to #collection, notice: 'saved'
else
render action: 'new'
end
end
def update
end
private
def collection_params
params.require(:collection).permit(:title)
end
end
collection.rb
class Collection < ActiveRecord::Base
belongs_to :user
has_many :posts
validates :title, presence: true
end
post.rb
has_many :collections
It seems like has_many or has_and_belongs_to_many associations are not correct? Should I be creating another model to act as an intermediary to then use
has_many :collections :through :collectionList?
If my association is wrong, can you explain what I need to change to make this work?
Also the next part in this is since this is not being created when the Post or Collection is created, I'm not sure the best way to handle this in the view. What is the best way to handle this, keeping my view/controller as clean as possible? I just want to be able to have a button on the Post#Show page that when clicked, allows users to add that post to a Collection of their own.
In such case you should use or has_and_belongs_to_many or has_many :through association. The second one is recommended, because it allows more flexibility. So now you should:
Create new model PostsCollections
rails g model PostsCollections post_id:integer collection_id:integer
and migrate it
Set correct model associations:
Something like:
class Post < ActiveRecord::Base
has_many :posts_collections
has_many :categories, through: :posts_collections
end
class Collection < ActiveRecord::Base
has_many :posts_collections
has_many :posts, through: :posts_collections
end
class PostsCollections < ActiveRecord::Base
belongs_to :post
belongs_to :collection
end
Then you'll be able to use
#collection.first.posts << #post
And it will add #post to #collection's posts
To add a post to a collection from view
Add a new route to your routes.rb, something like:
resources :collections do # you should have this part already
post :add_post, on: :member
end
In your Collections controller add:
def add_post
#post = Post.find(params[:post_id])
#collection = Collection.find(params[:id])
#collection.posts << #post
respond_to do |format|
format.js
end
end
As for views, you'll have to create a form to show a collection select and button to add it. That form should make POST method request to add_post_collection_path(#collection) with :post_id parameter.
You can read more explanations of how rails associations work in Michael Hartl's tutorial, because that subject is very wide, and can't be explained with short answer.

remove specific user from joined table

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'.

Rails nested resources creation - passing the user id

I have a set of nested resources consisting of users, books, and chapters. Here's how it looks.
Models
class User
has_many :books, dependent: :destroy
accepts_nested_attributes_for :books, allow_destroy: true
end
class Book
belongs_to :user
has_many :chapters, dependent: :destroy
accepts_nested_attributes_for :chapters, allow_destroy: true
end
class Chapter
belongs_to :book
end
Chapter Controller
def create
#chapter = #book.chapters.build(params[:chapter])
if #chapter.save
flash[:success] = "A new chapter created!"
redirect_to blah blah
else
render 'new'
end
end
protected
def get_book
#book = Book.find(params[:chapter][:book_id]) ||
Book.find(params[:book_id])
end
You might be wondering why I have that protected method. I'm trying to let users create chapters and books in separate pages and still have the convenience of having nested resources. So a user can create a chapter on the chapter creation page and associate the chapter with the right book via association form.
Currently I'm stuck because the chapter resource is not getting the user id it needs. I'm very new to web development so I might be doing some crazy things here. Any help would be greatly appreciated. I really want to get this to work.
EDIT: To give more detail on what I meant by "the chapter resource is not getting the user id it needs" - in the chapter model I wrote *validates :user_id, presence: true*. When I press the submit button on the chapter creation page, it gives an error saying user_id cannot be blank.
In order to be sure that the current user owns the chapter, and therefore the book, change the get_book method to
def get_book
#book = current_user.books.find(params.fetch(:chapter, {})[:book_id] || params[:book_id])
end
params.fetch makes sure that you don't get an exception when params[:chapter] is nil
I don't think the Chapter model should check that the user_id is present. Instead, the controller should have a before_filter that checks if the action is authorized for the current user.
Something like this:
class ChaptersController < ApplicationController
before_filter :authorized?, only: [:create]
def create
...
end
private
def authorized?
current_user && current_user.owns? Chapter.find(params[:id])
end
end
owns? would then be implemented on the User model, and current_user would be implemented in the ApplicationController.

conditional validation in one model but two different forms

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

Model and controller design approach for polymorphic assocation

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.

Resources