Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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/

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top