Rails: Nested resource and specifying the "nester" -


a company has many properties. property has 1 company.

in routes file got:

resources :companies   resources :property_managers end 

in property_manager_controller, create action looks (default scaffold implementation modified accommodate company):

def create    @property_manager = propertymanager.new(params[:property_manager]) @property_manager.company_id = params[:company_id]  respond_to |format|   if @property_manager.save     format.html { redirect_to company_property_managers_path, notice: 'property manager created.' }     format.json { render json: @property_manager, status: :created, location: @property_manager }   else     format.html { render action: "new" }     format.json { render json: @property_manager.errors, status: :unprocessable_entity }   end end 

end

is there way in not have explicitly set company_id, since known within context of url/route?

i guess following, not sure if it's better or not:

class propertymanagerscontroller < applicationcontroller   before_filter :find_company    def new     @property_manager = @company.property_managers.build   end    def create     @property_manager = @company.property_managers.build(params[:property_manager])     respond_to |format|       ...     end   end    private    def find_company     @company ||= company.find(params[:company_id])   end  end 

Comments