Tell me if the controller is used in a nested route in Rails 3

I made a nested route in a Ruby on Rails 3. project with the following routing:

resources :companies do
   resources :projects
end

Now I can go to the project contoller index method through example.com/projects/id or example.com/companies/id/projects/id, but both pages are displayed in exactly the same way. How can I change the project page in the second example to show only projects related to this company?

+5
source share
2 answers

I would change how you gain finds. Rails 3 is great for letting you do this because almost anything is possible.

-, , - :

before_filter :find_company

# your actions go here

private

  def find_company
    @company = Company.find(params[:company_id]) if params[:company_id]
  end

: Company, , , . , params[:company_id], @company.

, , @company. . before_filter, :

before_filter :scope_projects

find_company :

def scope_projects
  @projects = @company ? @company.projects : Project
end

, , "WOAH". . .

, projects, Project, @projects. scope_projects , " , -" " , -, ".

, , - :

<h1><% if @company %><%= @company.name %>'s<% end %> Projects</h1>

:

def optional_company
  if @company
    @company.name + "'s"
  end
end

hunk-o-logic :

<h1><%= optional_company %> Projects</h1>

, .

, .

+10

inherited_resources :

class ProjectsController < InheritedResources::Base
  belongs_to :company, :optional => true
end 
+1

All Articles