| Module | InheritedResources::BaseHelpers |
| In: |
lib/inherited_resources/base_helpers.rb
|
Base helpers for InheritedResource work. Some methods here can be overwriten and you will need to do that to customize your controllers from time to time.
Returns the association chain, with all parents (does not include the current resource).
This class allows you to set a instance variable to begin your association chain. For example, usually your projects belongs to users and that means that they belong to the current logged in user. So you could do this:
def begin_of_association_chain
@current_user
end
So every time we instantiate a project, we will do:
@current_user.projects.build(params[:project]) @current_user.projects.find(params[:id])
The variable set in begin_of_association_chain is not sent when building urls, so this is never going to happen when calling resource_url:
project_url(@current_user, @project)
If the user actually scopes the url, you should use belongs_to method and declare that projects belong to user.
This method is responsible for building the object on :new and :create methods. If you overwrite it, don‘t forget to cache the result in an instance variable.
This is how the collection is loaded.
You might want to overwrite this method if you want to add pagination for example. When you do that, don‘t forget to cache the result in an instance_variable:
def collection
@projects ||= end_of_association_chain.paginate(params[:page]).all
end
Responsible for saving the resource on :create method. Overwriting this allow you to control the way resource is saved. Let‘s say you have a PassworsController who is responsible for finding an user by email and sent password instructions for him. Instead of overwriting the entire :create method, you could do something:
def create_resource(object)
object.send_instructions_by_email
end
Returns if the controller has a parent. When only base helpers are loaded, it‘s always false and should not be overwriten.
This is how the resource is loaded.
You might want to overwrite this method when you are using permalink. When you do that, don‘t forget to cache the result in an instance_variable:
def resource
@project ||= end_of_association_chain.find_by_permalink!(params[:id])
end
You also might want to add the exclamation mark at the end of the method because it will raise a 404 if nothing can be found. Otherwise it will probably render a 500 error message.