Torvald_Junior
Torvald_Junior

Reputation: 1

Select context dynamically

in my models i have contexts like

acts_as_taggable_on :sport, :music

in the console i can do this

@student = Student.first
@student.sport_list = ("baseball, soccer")
@student.save

@student.music_list = ("rock, pop")
@student.save

@student.sport_list  
[baseball, soccer]

@student.music_list
[rock, pop]

All this works right but, in views I want to do this dynamic I catch in one string the context selected between others contexts by JavaScript for example:

mycontext = music

my doubt is: Its possible make dynamic do

@student.mycontext_list = "rock, pop"

because I get the following error undefined method `mycontext_list=' for Student:0xb4475d4c

greetings friends!!!

Upvotes: 0

Views: 200

Answers (3)

Amol Pujari
Amol Pujari

Reputation: 2349

its already given there mbleigh/acts-as-taggable-on

@student.set_tag_list_on(mycontext, "rock, pop")

Upvotes: 0

mshakhan
mshakhan

Reputation: 11

Try something like below:

 @student.send :"#{mycontext}_list=", "rock, pop"

Upvotes: 1

Ron
Ron

Reputation: 1166

The simplest solution is to define a method that accepts a string/symbol as an input

class Student
  def mycontext_list(string)
    self.send("#{string}_list".to_sym)
  end
end

Whatever string Javascript passes will then be used to call an appropriately named method (with _list appended to the end of it).

Upvotes: 0

Related Questions