2017-08-09 109 views
0

美好的一天!保存前检查用户输入

为了更好的理解而编辑。

第一个模型是库存,在这个模型中我有Product_Type,Product_Name和User_ID。

第二个模型我有由First_Name,Last_Name和Pin_Number组成的用户。

在我的库存页面上,我有一个表格用于检出Product_Type和Product_Name,也是用户放置其Pin_Number的地方。在提交时,它将检查它们键入的Pin_Number并在用户中进行验证模型,如果Pin_Number正确,它将创建一个具有所述Product_Type,Product_Name和User_ID(从提交的Pin_Number拉)的条目。

我只是想弄清楚如何验证它们提交的Pin_Number。

这就是为什么我认为我不得不做一些基于验证的验证和if语句。不知道如何去做。

我希望这可以消除任何混淆。

+0

看起来你需要'before_validation'回调。 –

+0

你有会话控制器,以便你知道'current_user'吗?用户每次输入密码时,用户是否在每次想要创建产品时都输入密码? – DRSE

回答

1

我只是想弄清楚如何验证他们提交的Pin_Number。

什么构成有效pin_number?只要它能让你成功查找User?如果用户输入另一个用户的pin_number会怎么样?这被认为是“有效的”?有些事情需要考虑...

如果你想在你的问题中加入你提交的params表单,它会有帮助。但是,我们可以做一些猜测工作。

所以,让我们假设PARAMS看起来像:

{..., "inventory"=>{"product_type"=>"foo", "product_name"=>"Bar"}, "pin_number"=>5, ...} 

在你的控制器,你可能会做这样的事情:

if @user = User.find_by(pin_number: params[:pin_number]) 
    @inventory = Inventory.new(inventory_params) 
    @inventory.user = @user 
    if @inventory.valid? 
    @inventory.save 
    # perhaps do some other stuff... 
    else 
    # handle the case where the `@inventory` is not valid 
    end 
else 
    # handle the case where the `@user` was not found 
end 

这里假设你有这样的:

private 

    def inventory_params 
    params.require(:inventory).permit(:product_type, :product_name) 
    end 

在您的Inventory模型中,您可能想要做些喜欢的事情E(我很抱歉,我不是on Rails的5呢,所以一些语法可能不正确):

class Inventory < ActiveRecord::Base 

    validates :user_id, 
      :product_type, 
      :product_name, 
      presence: true 

    belongs_to :user 

end 

你可能还需要考虑在User.pin_number添加索引,如果你打算做很多发现它。

+0

请参阅已编辑的问题。 – Allen

+0

这就是我一直在寻找的,我无法弄清楚如何去做。但这个例子就是我的想法。谢谢! – Allen

+0

很高兴提供帮助。此外,你澄清你的问题真的很棒 - 超级有用! – jvillian

0

不知道我是否有问题,但听起来像是一个自定义验证器。

您可以在“Custom Validators

而且,考虑移动类,你会建立到一个问题,这是使它成为一个伟大的方式自定义验证详细了解Rails的官方文档中的自定义验证可重复使用的。您可以在this StackOverflow questionthis nice tutorial找到更多信息。

+0

谢谢我会检查出来。 – Allen