![](/img/trans.png)
[英]Rails STI. How do I count the number of votes of type Upvote or Downvote for associated model?
[英]How do I so a select input for a STI column in a Rails model?
我在type
列上有一個具有單表繼承的模型:
class Pet < ActiveRecord::Base
TYPES = [Dog, Cat, Hamster]
validates_presence_of :name
end
我想在新頁面和編輯頁面上提供一個<select>
下拉列表:
<% form_for @model do |f| %>
<%= f.label :name %>
<%= f.text_input :name %>
<%= f.label :type %>
<%= f.select :type, Pet::TYPES.map { |t| [t.human_name, t.to_s] } %>
<% end %>
這給了我以下錯誤:
ActionView::TemplateError (wrong argument type String (expected Module))
我讀到一個建議為字段#type
使用別名,因為Ruby認為保留字與#class
相同。 我都嘗試過
class Pet < ActiveRecord::Base
...
alias_attribute :klass, :type
end
和
class Pet < ActiveRecord::Base
...
def klass
self.type
end
def klass=(k)
self.type = k
end
end
兩者都不起作用。 有什么建議么? 奇怪的是,它在我的機器上運行正常(RVM上為MRI 1.8.6),但在登台服務器上失敗(MRI 1.8.7不在RVM上)。
ryan bates的“建議”(比其他人更了解rails)與您的實現之間的主要區別是,建議使用通過方括號(“ self [:type] =”)直接訪問屬性,而不是使用方法調用(“ self.type =”)
因此,嘗試類似:
class Pet < ActiveRecord::Base
...
def klass
self[:type]
end
def klass=(k)
self[:type] = k
end
end
您也可以嘗試將STI所使用的列名稱更改為不同於type
。
根據railsapi.com
,它可以在子類中設置,因此只需在您的pet
模型中添加以下內容:
self.inheritance_column = "type_id"
我只是在猜測...所以很抱歉,這是完全錯誤的。
如果您絕對必須執行此操作,則可以在您的控制器中執行以下操作:
@pet = Pet.new(params[:pet])
@pet[:type] = params[:pet][:type]
IMO,這樣做時最好既露骨又痛苦,因為在這種情況下即時更改類型感覺真是個壞主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.