【问题标题】:Validate a value from a different model验证来自不同模型的值
【发布时间】:2013-05-29 22:42:47
【问题描述】:

我是 Rails 新手,所以我有一个新手问题。

我们有一个表单可以让管理员设置一个如下所示的新用户:

<%= form_for :user, :url => url_for(:action => 'create_user', :account_id => @account.id, :hide_form => 1), :html => {:name => 'new_user_form', :id => 'new_user_form', :remote => true} do |f| %>
  First Name:
  <% f.text_field 'first_name' %><br/>
  Last Name:
  <%= f.text_field 'last_name' %><br/>
  Username:
  <%= f.text_field 'login' %><br/>
  Email:
  <%= f.text_field 'email' %><br/>
  Agency Code:
  <%= text_field_tag 'agency_code', @default_agency_code %><br/>

  <div class="button-bar">
    <%= f.submit :id => "submit_button" %>
  </div>
<% end %>

到目前为止,一切都很好。提交表单时调用的操作将所有表单值推送到 User 对象并将其保存到数据库中:

def remote_create_user
  @user = User.new(params[:user])
  @user.agency = Agency.find{|agency| agency.product_code == params[:agency_code]}
  if @user.valid? and @user.save
    # Move some stuff around for the new user
  else
    @error = "Failure to Save:"
    @user.errors.full_messages.each {|msg| @error += " - #{msg}"}
  end
end

我的理解是视图中以&lt;%= form_for :user 开头的行让ERB 视图知道使用User 模型中指定的验证逻辑来​​验证直接对应于User 类的所有表单字段。

但是,表单中的最后一个字段 (Agency Code: &lt;%= text_field_tag 'agency_code', @default_agency_code %&gt;&lt;br/&gt;) 与 User 模型中的属性不对应。相反,它对应于Agency.product_codeAgency 模型为此属性定义了验证。我如何告诉 Rails 使用 Agency 模型中的验证逻辑来​​处理这个字段?如果没有办法直接执行此操作,我如何将验证直接添加到代理代码文本字段?

【问题讨论】:

    标签: ruby-on-rails ruby validation ruby-on-rails-3.2 ruby-1.8.7


    【解决方案1】:

    你可以简单地使用

    @user.agency = Agency.find_by_id{|agency| agency.product_code == params[:agency_code]}
    

    在您的用户模型中,

    validates :agency_id, :presence => true
    

    find_by_id 在这种情况下会比简单的 find 工作得更好,因为如果找不到模型,它会返回 nil

    【讨论】:

    • 感谢您这么快回复!一个想法仍然让我有些困惑:User 模型的更改如何让 Rails 知道在 Agency 模型中查找验证?
    • 如果我没记错的话,看看你的代码,你似乎在选择一个现有的机构,而不是在创建用户时更新一个。在这种情况下,如果找到代理将始终有效,因此实际上您要验证用户属性 - 他应该有代理。代理模型没有验证,它在用户身上 - 它需要有一个代理(因此,agency_id 不能为空)。如果您在添加用户后修改代理,则需要改用nested form
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多