简体   繁体   English

如何验证不与db列对应的参数?

[英]How can I validate params that don't corrospond to a db column?

I have a model User with a string attribute name . 我有一个模型User ,其字符串属性为name On my form to create a new User , it's easy to validate the name attribute: 在我的表单上创建一个新的User ,很容易验证name属性:

models/user.rb 车型/ user.rb

validates :name, presence: true, length: {maximum: 13}

users_controller.rb users_controller.rb

private

def user_params
  params.require(:user).permit(:name, :words)
end

However, I want to validate a param that isn't an attribute or db column. 但是,我想验证不是属性或数据库列的参数。 On my form I have a textbox that submits params["words"] as a string. 在我的表单上,我有一个文本框,它以字符串形式提交params["words"] I know the param is being submitted because I can interact with it using binding.pry . 我知道参数已提交,因为我可以使用binding.pry与之交互。 But if I try to validate it the same way as Name, nothing happens. 但是,如果我尝试以与Name相同的方式进行验证,则不会发生任何事情。 The form submits with or without words . 提交表格时不带words How can I validate a param that isn't an attribute? 如何验证不是属性的参数?

my form: 我的表格:

<%= form_for @user, :url => users_path do |f| %>
  <%= f.text_field :name %>
  <input id="words" name="words">
  <%= f.submit "Submit", class: "btn" %>
<% end %>

If you want to perform model validations that include :words then you need to add :words as a virtual attribute in your User.rb file so the model has access to it. 如果要执行包含:words的模型验证,则需要在User.rb文件中添加:words作为虚拟属性,以便模型可以访问它。 You can do that simply by adding this line to your User.rb file: 您只需将以下行添加到User.rb文件中即可:

attr_accessor :words

Then your model can now perform validations on it such as: 然后,您的模型现在可以对其执行验证,例如:

validates_presence_of :words

You also need to ensure that the :words param belongs to :user and is being sent as params["user"]["words"] 您还需要确保:words参数属于:user并作为params["user"]["words"]


Edit: 编辑:

To get your form to post the :words parameter nested under :user change your form input to: 要使您的表单发布嵌套在:user下的:words参数,请将表单输入更改为:

<input id="words" name="user[words]">

or since the user model now has the virtual attribute :words you can set your form the rails way. 因为用户模型现在具有虚拟属性:words,所以您可以将表单设置为rails方式。

<%= f.text_field :words %>


APIDock reference on attr_accessors: http://apidock.com/ruby/Module/attr_accessor attr_accessors上的APIDock参考: http ://apidock.com/ruby/Module/attr_accessor

Virtual Attribute Reference: http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Classes_Objects_and_Variables_Virtual_Attributes.html 虚拟属性参考: http : //www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Classes_Objects_and_Variables_Virtual_Attributes.html

该表单应提交params['user']['words']而不是params['words'] ,并且您的User模型应具有attr_accessor :words

尝试将您的值放在params[:user][:words]而不是params[:words]然后在模型中添加attr_accessor :words

You can do it adding the words attribute to User class. 您可以将words属性添加到User类。

class User < ActiveRecord::Base
  attr_accessor :words

  validates :words, presence: true, length: {maximum: 13}

  def initialize(arguments = {}, options = {})
    self.words = arguments.delete :words
    super
  end
end

But, override ActiveRecord initialize method isn't recommended. 但是,不建议覆盖ActiveRecord初始化方法。 It seems that this validation should occurs only in this action. 似乎此验证仅应在此操作中进行。

The correct approach should be use a Form Object. 正确的方法应该使用表单对象。 You can learn more here: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ 您可以在此处了解更多信息: http : //blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RSpec controller 测试无法获取 id 参数。 我不知道如何解决这个问题 - RSpec controller test can't get id params. I don't know how to fix this 如何验证视图中的参数? - How can validate params in the view? 为什么我不需要将参数传递给 article_params? - How come I don't need to pass params to article_params? 如何通过“和”(而不是“或”)在数据库中查询参数 - How can I query my db for params by “and” instead of “or” 如果数据库中不存在 params[:id],我应该如何编写代码 - How should I write code if a params[:id] doesn't exist in the db 如何在不验证其余属性/列的情况下验证和更新1个属性/列? - How can I validate and update 1 attribute/column, without validating the rest? 在Rails上的ruby中播种db,由于缺少我不使用的方法而无法初始化对象 - seeding a db in ruby on rails, can't initialize a object because of a method missing I don't use 为什么我不能在params中做每一个? - why I can't do each in params? 为什么我不能使用参数创建 object? - Why i can't create object with params? 我已经使用 active_scaffold 和回形针上传了一个文件,通过更新操作,但不知道如何提取参数 - I've uploaded a file using active_scaffold and paperclip, passing through update action, but don't know how to extract the params
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM