Access a view helper for a model in rails

后端 未结 2 1509
猫巷女王i
猫巷女王i 2020-12-17 04:12

I have an Adult model with a name attribute.

If the user is logged in, I want the Adult.name to only return the first name.

Is there a way to have helpers ti

相关标签:
2条回答
  • 2020-12-17 05:10

    in your Adult model you can add

    def name
      self.first_name
    end
    

    so when you find an Adult, like

    a = Adult.last
    puts a.name #will print a.first_name
    

    Well, for a better explanation.. paste some code!

    0 讨论(0)
  • 2020-12-17 05:13

    Just explicitly include the helper in your model

    # app/helpers/adults_helper.rb
    module AdultsHelper
      def say_hello
        "hello, world!"
      end
    end
    
    # app/models/adult.rb
    class Adult < ActiveRecord::Base
      include AdultsHelper
    
    end
    

    Test in console

    $ script/console
    >> a = Adult.new
    # => #<Adult id:...>
    >> a.say_hello
    # => "hello, world!"
    
    0 讨论(0)
提交回复
热议问题