Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a view helper for a model in rails

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 tied to a model where you could specify Adult.helper.name?

Or a least have helpers namespaced to a model?

like image 794
Christopher Avatar asked Dec 12 '22 22:12

Christopher


2 Answers

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!"
like image 161
maček Avatar answered Jan 01 '23 07:01

maček


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!

like image 39
amrnt Avatar answered Jan 01 '23 08:01

amrnt