2012-06-04 37 views
0

在我的模型有背景喜歡選擇方面動態

acts_as_taggable_on :sport, :music 

在控制檯中我能做到這一點

@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] 

所有這些作品的權利,但是,在視圖中我想這樣做動態 我在一個字符串中捕獲通過JavaScript在其他上下文之間選擇的上下文,例如:

mycontext = music 

我的疑問是:它可以進行動態做

@student.mycontext_list = "rock, pop" 

,因爲我碰到下面的錯誤未定義的方法`mycontext_list =」的學生:0xb4475d4c

問候朋友!

回答

1

嘗試像下面:

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

senk你了! 100%有用 –

0

最簡單的解決方案是定義接受字符串/符號作爲輸入的方法

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

無論串的Javascript通過將被用來調用一個適當命名的方法(將_list附加到它的末尾)。

+0

非常感謝! Tnxs羅恩和mshakhan幫我...我希望在未來的幫助有人大聲笑! –

+0

如果您接受問題的答案,那對每個人都有幫助。 – Ron