【问题标题】:accepts_nested_attributes_for :reject_if to trigger another methodAccepts_nested_attributes_for :reject_if 触发另一个方法
【发布时间】:2011-02-19 03:52:00
【问题描述】:

我有一个使用 formtastic_cocoon(jquery 版本的 formtastic)的多级嵌套表单。

我正在尝试在

的意义上进行一些验证 如果值 is_numeric 做 插入数据库 否则做 基于文本的数据库查找 插入 id 作为关联 结尾

我希望accepts_nested_attributes_for 有一个:if 选项,但显然只有:reject_if。

有没有办法像我描述的那样创建验证,作为accepts_nested_attributes_for 的一部分??

-----------根据祖宾的回复更新了-------- --------

我相信 Zubin 的方法是正确的,但我似乎无法让它正常工作。我使用的方法是

def lookup_prereq=(lookup_prereq) 如果lookup_prereq.blank 则返回? case lookup_prereq 当lookup_prereq.is_a?(Numeric) == true self.task_id = lookup_prereq 别的 self.task = Task.find_by_title(lookup_prereq) 结尾 结尾

当我触发此函数时,self.task_id 将作为“0”而不是 Task.id 放入数据库中。

我想知道我是否遗漏了其他东西。 我不完全确定该方法实际上正在被调用。我不应该说吗

lookup_prereq(attr[:prereq_id)

在某个时候?

-------------------进一步编辑----------- 我认为据我所知,只有当它的名称与数据库的值同名时才会调用该方法,因此我将方法更改为

def 完成任务=(完成任务)

不幸的是,这仍然导致 0 作为数据库中的值。

【问题讨论】:

    标签: ruby-on-rails nested-attributes


    【解决方案1】:

    听起来您需要嵌套模型中的方法来处理它,例如:

    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
    

    【讨论】:

    • 感谢 Zubin,我认为这与我正在寻找的非常接近,但我似乎无法让它正常工作。我已经用你的代码更新了这个问题,适应了我正在寻找的东西,但由于某种原因,我没有让查找 find_by_task 返回正确的 id,并且数据库总是得到 0。你应得的我认为获得正确答案的要点,但我无法确定该方法是否正确运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2016-09-11
    • 2014-06-14
    • 2011-05-18
    相关资源
    最近更新 更多