Another one of those "Wow! that worked" moments.
March 17th, 2009
Rails, and therefore ruby, are always amazing me. Just today, I was working on a site that had a job object. The job belonged to both a company and a project. Now, normally, given restful routing, you have something like this as your url
http://www.mycoolsite.com/projects/1/jobs/4/edit
or
http://www.mycoolsite.com/companies/2/jobs/4/edit
and this will load up the form for a job object. In my jobs controller, I have a method as such:
class JobsController < ApplicationController
before_filter :get_dependencies
def get_dependencies
#requests will come in from either projects or companies
@project = Project.find(params[:project_id]) unless params[:project_id].nil?
@company = Company.find(params[:company_id]) unless params[:company_id].nil?
@parent = @project || @company
end
end
and depending on whether the request came in from a context of a company or a project, the @parent object will contain that object. The form can also determine if the the parent object is a company or a project and pre-fill that blank with the correct information. All of this is pretty standard. The part that I was stuck on was linking to these forms. Given these urls:
http://www.mycoolsite.com/companies/2/jobsor
http://www.mycoolsite.com/projects/1/jobs
How can I link to the add or edit actions without having to do something un-dry like this:
- if @parent.is_a? Project =link_to 'Edit', edit_project_job_path(@parent, job) - else =link_to 'Edit', edit_company_job_path(@parent, job)
Well, the solution is simple, clear & concise—Would you expect anything less from RoR? :)
link_to 'Edit', edit_polymorphic_path([@parent,job])
This will automatically determine the parent object and it’s associated restful path along with the current jobs restful path.
Sorry, comments are closed for this article.