2014-12-03 118 views

回答

0

你調用cli對象的方法atributo。如果該對象沒有該方法,那麼你會得到錯誤。

你在這裏做的是設置一個局部變量的字符串「名稱」,然後遍歷一些集合並調用對象上的某種方法。我不認爲這就是你打算做的。我需要更多的信息來指導你正確的方向。

0

當您定義atributo時,它將成爲一個獨立變量,與任何模型無關。

當您致電cli.atributo時,試圖找到與cli對象關聯的atributo方法,該方法不存在。如果需要從對象訪問atributo,請在模型中定義它。

0

實際上是試圖把它打印出來,它可以把它打印出來的唯一辦法是,如果有atributo

的方法嘗試

<% atributo = "name" %> 

或者更好的是,設置的值attributo(如@attributo)在您的控制器中。該視圖只能用於查看,而不能實際設置變量。

3

這不完全是Ruby的工作原理。例如:

attribute = "name" 

client = Client.first 
client.attribute # => Calls "attribute" method on client 

你想要的是動態地調用一個方法:

attribute = "name" 

client = Client.first 
client.send(attribute) # => Calls "name" method on client. 

更妙的是剛剛讀你要操作的屬性:

attribute = "name" 

client = Client.first 
client[attribute] # => Value of "name" attribute 
1

你想要什麼大概是:

<% atributo = "name" %> 
<% @clients.each do |cli| %> 
    <%= clo[atributo] %> 
<% end %> 

因此您動態調用cli上的方法#name

+0

其實,如果這將是你需要做的clo.send(attributo)此外,正如我在答覆中提到這種沉重的意圖業務邏輯可能是更好的控制器 – Kalman 2014-12-03 19:26:33

+0

@KalmanHazins這是一個rails問題,所以這可能是一個'ActiveRecord'模型,因此將支持傳遞符號和字符串作爲鍵來獲取表列的值。爲什麼你說這是「繁重的商業邏輯」,如果它似乎是一種在視圖上渲染模型的動態方法? – rafb3 2014-12-03 19:39:45

+1

的確如此。根據你的假設 - 你是對的。否則,在你的視圖(使用obj.send(:stuff))中進行元編程是非常糟糕的。那可能就是我...... – Kalman 2014-12-03 19:42:31

0

我認爲這可能是你想要什麼:

<% @clients.each do |cli| %> 
    <%= cli.name %> 
<% end %> 
相關問題