New Discussion

Notifications

You’re not receiving notifications from this thread.

"Controller action should call one model method..." (?)

1
Rails

Controller action should call one model method other than an initial find or new
This inspection warns if a controller action contains more than one model method call, after the initial .find or .new. It’s recommended that you implement all business logic inside the model class, and use a single method to access it.

I keep getting this warning on my IDE when I do stuff like:

application_controller.rb (everything inside the unless is flagged)

class ApplicationController < ActionController::Base
  helper_method :check_user_login

  def check_user_login
    @user = User.find(current_user.id)

    unless @user.has_profile(@user.id)
      @user.create_profile(@user.id)
    end
  end
end

user.rb

class User < ApplicationRecord
  has_one :user_profile

  def has_profile(id)
    UserProfile.exists?(user_id: id)
  end

  def create_profile(id)
    new_profile = UserProfile.new
    new_profile.user_id = id
    new_profile.first_name = 'New'
    new_profile.last_name = 'User'
    new_profile.avatar_url = 'default.png'
    new_profile.save
  end
end

Whats the correct way of doing this then?

Ok, I got rid of it... I refactored as follows:

application_controller.rb

class ApplicationController < ActionController::Base
  def check_user_login
    @user = User.find(current_user.id)

    @user.profile?
  end
end

user.rb

class User < ApplicationRecord
  has_one :user_profile

  def profile?
    create_profile unless UserProfile.exists?(user_id: id)
  end

  def create_profile
    UserProfile.create([{ new_profile }])
  end
end
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 88,834+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.