Accepts_nested_attributes_for :reject_if 触发另一个方法
我有一个使用 formtastic_cocoon (formtastic 的 jquery 版本)的多级嵌套表单。
我试图做一些验证,因为
if value is_numeric do insert into database else do database lookup on text insert id as association end
我希望 Accept_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 作为数据库中的值。
I've got a multi-level nested form using formtastic_cocoon (jquery version of formtastic).
I am trying to do some validation in the sense of
if value is_numeric do insert into database else do database lookup on text insert id as association end
I was hoping tha the accepts_nested_attributes_for would have an :if option, but apparently there is only the :reject_if.
Is there a way to create a validation like I describe as part of the accepts_nested_attributes_for??
-----------------------Updated as per Zubin's Response ---------------------------
I believe Zubin is on the right track with a method, but I can't seem to get it working just right. The method I am using is
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
When I trigger this function, the self.task_id is being put in the database as '0' rather than the Task.id.
I'm wondering if I'm missing something else.
I'm not completely sure that the method is actually being called. Shouldn't I need to say
lookup_prereq(attr[:prereq_id)
at some point?
-------------------further edit -----------------------
I think from what I can find that the method is called only if it is named with the same name as the value for the database, therefore I've changed the method to
def completed_task=(completed_task)
Unfortunately this is still resulting in 0 as the value in the database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您需要在嵌套模型中使用一个方法来处理该问题,例如:
Sounds like you need a method in your nested model to handle that, eg: