Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails calling a controller action from the console

I have a controller sessions that can create session. I'd like to call it from the console, like controller.create. Here is the action:



  def create  
    #raise request.env["omniauth.auth"].to_yaml

    auth = request.env["omniauth.auth"]  
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)  
    user.create_or_update_profile(auth)
    session[:user_id] = user.id 

    if user.needs_to_create_profile?
      redirect_to new_profile_path, :notice => "Signed in!. We just need your contact e-mail"
    else
      redirect_to root_url, :notice => "Signed in!"  
    end
  end 
like image 481
daniel Avatar asked Dec 09 '10 16:12

daniel


People also ask

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended. Read into Model View Controller (MVC). To keep things independent.

What is action controller rails?

Action Controller is the C in MVC. After the router has determined which controller to use for a request, the controller is responsible for making sense of the request and producing the appropriate output.

What decides which controller receives which requests in Rails?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.


1 Answers

From the console:


   include ActionController::TestProcess
   @request = ActionController::TestRequest.new
   @response = ActionController::TestResponse.new
   @controller = SomeController.new

   @request.env["omniauth.auth"] = {'provider' => "twitter", 'uid' => "1234", 'user_info' => {'name' => "foo"}}

   app.get "/signup" etc

From rspec:



it "should allow login" do
    request.env["omniauth.auth"] = {'provider' => "twitter", 'uid' => "1234", 'user_info' => {'name' => "foo"}}
    post :create
    puts @current_user.name
    assigns(@current_user).should_not be_nil
  end

like image 191
daniel Avatar answered Nov 09 '22 02:11

daniel