[英]custom attributes version of accepts_nested_attributes_for with reject_if
[英]accepts_nested_attributes_for :reject_if to trigger another method
我有一個使用formtastic_cocoon(formtastic的jquery版本)的多層嵌套表單。
我正在嘗試從某種意義上進行驗證
if value is_numeric do insert into database else do database lookup on text insert id as association end
我希望accepts_nested_attributes_for可以有一個:if選項,但是顯然只有:reject_if。
有沒有一種方法可以創建像我作為accepts_nested_attributes_for的一部分描述的驗證?
-----------------------根據Zubin的回應進行更新---------------------- -----
我相信Zubin的方法是正確的,但我似乎無法使其正常工作。 我正在使用的方法是
def lookup_prereq=(lookup_prereq) return if lookup_prereq.blank? case lookup_prereq when lookup_prereq.is_a?(Numeric) == true self.task_id = lookup_prereq else self.task = Task.find_by_title(lookup_prereq) end end
當我觸發此函數時,self.task_id被放置為數據庫中的“ 0”,而不是Task.id。
我想知道我是否還缺少其他東西。 我不完全確定該方法實際上在被調用。 我不是應該說
lookup_prereq(attr[:prereq_id)
在某一點?
-------------------進一步編輯-----------------------我想發現該方法僅在使用與數據庫值相同的名稱時才被調用,因此我將方法更改為
def completed_task=(completed_task)
不幸的是,這仍然導致數據庫中的值為0。
聽起來您需要在嵌套模型中使用一種方法來處理該方法,例如:
class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author
def lookup_author=(lookup_author)
return if lookup_author.blank?
case lookup_author
when /^\d+$/
self.author_id = lookup_author
else
self.author = Author.find_by_name(lookup_author)
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.