views:

142

answers:

3

In my Ruby on Rails app, I've got:

class AdminController < ApplicationController
  def create
    if request.post? and params[:role_data]
      parse_role_data(params[:role_data])
    end

  end
end

and also

module AdminHelper
  def parse_role_data(roledata)
    ...
  end
end

Yet I get an error saying parse_role_data is not defined. What am I doing wrong?

A: 

Shouldn't you be accessing the parse_role_data through the AdminHelper?

Update 1: check this http://www.johnyerhot.com/2008/01/10/rails-using-helpers-in-you-controller/

eglasius
While that's a useful tip for using niceties like the formatting-related helpers provided by ActionView, integral business code really does belong in the model.
Luke
+2  A: 

Helpers are mostly used for complex output-related tasks, like making a HTML table for calendar out of a list of dates. Anything related to the business rules like parsing a file should go in the associated model, a possible example below:

class Admin < ActiveRecord::Base
  def self.parse_role_data(roledata)
    ...
  end
end

#Call in your controller like this
Admin.parse_role_data(roledata)

Also look into using (RESTful routes or the :conditions option)[http://api.rubyonrails.org/classes/ActionController/Routing.html] when making routes, instead of checking for request.post? in your controller.

Luke
Hmmm... but I have an admin controller but not an admin model.
alamodey
You can easily just define the model with no child class, ie. `class Admin`. If the file doesn't exist, just make a file called `admin.rb` in the models directory.
Luke
Now I get "undefined method `parse_role_data' for Admin:Class".
alamodey
Are you defining the method with `self` in front of it, like `def self.parse_role_data(roledata)`?
Luke
A: 

From the looks of if you're trying to create a UI for adding roles to users. I'm going to assume you have a UsersController already, so I would suggest adding a Role model and a RolesController. In your routes.rb you'd do something like:

map.resources :users do |u|
    u.resources :roles
end

This will allow you to have a route like:

/users/3/roles

In your RolesController you'd do something like:

def create
    @user = User.find_by_username(params[:user_id])
    @role = @user.roles.build(params[:role])
    if @role.valid?
        @role.save!
        redirect_to @user
    else
        render :action => 'new'
    end
end

This will take the role params data from the form displayed in the new action and create a new role model for this user. Hopefully this is a good starting point for you.

jonnii
True, but hopefully it'll highlight what he's doing wrong. Wanting to use helpers in your controllers is normally an indication that you're not doing enough in the model.
jonnii