[英]Rails: adding a field to a model-based object before passing it to the view
我的Rails應用程序中有一個“單詞”模型。 在我的單詞控制器的索引操作中,我從數據庫中獲取了一組單詞並查詢了它們的定義。 我不在數據庫中存儲定義,也不希望將定義存儲在數據庫中。 但是,我希望控制器將每個單詞的定義添加到單詞對象,然后再將其移交給視圖。
換句話說,我的“單詞”對象包含以下字段:
t.integer "user_id"
t.text "notes"
t.datetime "created_at"
t.datetime "updated_at"
t.string "word_name"
單詞controller的作用類似於
@words = current_user.words
而且視圖可以顯示類似
<% @words.each do |w| %>
<%= w.word_name %>
<%= w.notes %>
<% end %>
我想讓控制器做
@words.each do |w|
w.definition = "blah"
end
然后在我的視圖中顯示:
<%= word.definition %>
但是,Word類型的對象沒有“定義”字段,因此上述方法不起作用。 您對實現此目標的最干凈方法有建議嗎?
謝謝
向單詞模型添加虛擬屬性。
http://railscasts.com/episodes/16-virtual-attributes
這樣簡單的事情
class Word < ActiveRecord::Base
attr_accessor :definition
.... rest of class....
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.