Should I use class method or instance method, and why?

后端 未结 4 556
生来不讨喜
生来不讨喜 2021-02-02 03:06

In my Rails app, when creating a business I have a form that has the following field:

   <%= check_box_tag(:default_company) %> 
   <%= label_tag(:defau         


        
4条回答
  •  心在旅途
    2021-02-02 03:53

    As their name suggests, instance methods on a model should be used for logic/operations that relate to a specific instance of a user (the one on which the method is called.) So you could think of setting the default company for a user as an instance method on User. Class methods are for things which don't operate on an individual instance of a model or for cases where you don't have the instance available to you. e.g. you might have a class method to tidy up your database such as User.purge_expired_users which would not apply to an individual user object.

    e.g.

    class User
      def set_default_company(company)
        exists = DefaultCompany.find(self.id)
        if exists
          exists.update_attributes(company: company)
        else  
          DefaultCompany.create(company: company, user: self)
        end
      end
    end
    

    then your controller method would look like:

    def create
      @company = Company.new(params[:company])
    
      if @company.save
        if params[:default_company]
          current_user.set_default_company @company
        end
        flash[:notice] = "Company was successfully created."
        redirect_to @company
      else
        redirect_to new_company_path
      end
    end
    

    Alternatively, you could think of the relationship from the other perspective and put an instance method on Company e.g. company.set_as_default_for(user).

提交回复
热议问题