2016-11-03 163 views
1

我想在创建记录时根据特定字段显示弹出式消息/ update some other table alsoRAILS:弹出/警告/消息before_create

有没有办法使用验证或操作链接来做到这一点?

我想要做的事象下面这样:

validates :fieldc, if: :should_update?, message: "Update fielda and fieldb in tablex also" 

bef should_update? 
    fieldc == "req_value" 
end 

我相信上面的验证将无法正常工作。但我想显示弹出窗口,如果fieldc == req_value和记录应该创建。有没有办法做到这一点?

谢谢。

编辑: 我可以这样做吗?

after_create :update_tablex 
    def update_tablex 
     if self.should_update? 
     flash[:notice] = 'Please update fielda and fieldb in tablex also' 
     else 
     flash[:notice] = 'Record updated successfully.' 
     end 
    end 


def should_update? 
    fieldc == "req_value" 
end 

但是荫仍然得到NameError (undefined local variable or method 'flash' for #)

+0

能否请您更清楚了吗?你的形式是什么意思? – Mounika

+0

保持简单,是否有办法在rails模块中显示弹出消息来执行创建新操作? – Mounika

回答

1

这真是一个控制器问题,应在控制,而不是模型来解决。该模型从不负责控制所查看内容的逻辑以及工作流程的进展情况。最好的办法是设置一个显示他们需要做什么的Flash消息,并将其重定向到tablex编辑视图。

在创建方法......

def create 
    ... 
    if @record.save 
    if @record.should_update? 
     flash[:notice] = 'Please update fielda and fieldb in tablex also' 
     redirect_to edit_tablex_path(@record.tablex) 
    else 
     flash[:notice] = 'Record updated successfully.' 
     redirect_to @record 
    end 
    else 
    render :new 
    end 
end 
+0

这是一个非常可靠的方法 –

+0

我收到以下错误:'NameError(未定义的局部变量或方法'闪存'为#)' – Mounika

+0

对不起,在我的第五行中忘记了一个等号。我编辑了答案。 – SteveTurczyn