简体   繁体   中英

How to dynamically call accessor methods in my model object from view

I have a model:

class Mymodel < ActiveRecord :: Base

  attr_accessible :the_date, :the_time, :the_event

  def the_date
    ...
  end

  def the_time
    ...
  end

  def the_event
    ...
  end
...
end

My controller holds a array of methods names, which is used by view:

class Mycontroller < ApplicationController

  @methods=['the_date', 'the_time', 'the_event']
  ...
end

in my view index.html.haml , I would like to dynamically access the model methods:

%td
  -index=SOME_USER_INPUT
  =mymodel.@methods[index] /IT DOES NOT WORK HERE!!

But, I can not dynamically call the model methods in this way: mymodel.@methods[index] , how to have dynamical method call based on my sample code??

@methods is an instance variable of your controller, not of your model. Assuming you want to call the method, try this:

=mymodel.send(@methods[index])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM