开发者

Call methods from other controllers in rails

I'm trying to call a method from within another controller and getting a no method error.

So I have two controllers Jobs and Admin, I'm trying to call:

<% @jobs.each do |job| %>

I'm putting this command in the admin contoller's view, within the actual controller file for admin I have:

  # GET /jobs
  # GET /jobs.xml
  # GET /admin
  def index
    @jobs = Job.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @jobs }
    end

Which I thought would pull everything I needed over yet I'm still getting a nomethoderror, so how should I include 开发者_如何学运维the jobs controller into the admin one?


from the code you posted, it appears that you are not using a query to get the jobs that you want from the database, eg

@jobs = Job.all

Job.all is an activerecord query that gets all the available records from the database. It sounds like you may be confused about how all the MVC pieces are intended to work together.

First, you should not be sharing methods across controllers, in reality your controllers will have very little code.

Rails will route a request, and look for an action defined in the controller, if it doesn't find one, it will go to the views folder and get the template of that action name there, eg a request to Jobs#index will look for an index action in the controller, and then if it isnt there, look for the views/jobs/index.erb template to render. So if you are serving static data and don't need to look up data, you dont even need an action in your controller. Often though, the action is needed because it is in the controller that you do your database and model lookups, and then pass those instance variables to the view. Keep all database queries and model actions out of the views.

def index
  @jobs = Job.all
end

and in the view

@jobs.each do |job| ...

The respond_to block is totally unnecessary unless you want to return a differently formatted template than html, like xml or json for a web service.


You have not defined jobs action in Admin controller. You are loading @jobs in index action of Admin controller. If you want this work, rename index action of the Admin controller to jobs and add that route. One way you could add a route is by adding a line in config/routes.rb.

match '/jobs' => 'admin#jobs'

Read through this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜