How to use concerns in Rails 4

后端 未结 6 1878
甜味超标
甜味超标 2020-11-22 06:57

The default Rails 4 project generator now creates the directory \"concerns\" under controllers and models. I have found some explanations about how to use routing concerns,

6条回答
  •  眼角桃花
    2020-11-22 07:35

    In concerns make file filename.rb

    For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by

    module TestConcern 
      extend ActiveSupport::Concern
    
      def checkattributes   
        if self.has_attribute?(:created_by)
          self.update_attributes(created_by: 1)
        end
        if self.has_attribute?(:updated_by)
          self.update_attributes(updated_by: 0)
        end
      end
    
    end
    

    If you want to pass arguments in action

    included do
       before_action only: [:create] do
         blaablaa(options)
       end
    end
    

    after that include in your model like this:

    class Role < ActiveRecord::Base
      include TestConcern
    end
    

提交回复
热议问题