【问题标题】:has_one belongs_to association attribute validationhas_one belongs_to 关联属性验证
【发布时间】:2017-07-13 02:41:55
【问题描述】:

我使用设计进行用户身份验证。有两个模型 UserProfile 像这样相互关联

  #app/model/user.rb
  class User < ApplicationRecord
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable

    has_one :profile, dependent: :destroy
    enum role: [:admin, :seller, :buyer]
  end

 #app/model/profile.rb
  class Profile < ApplicationRecord
    belongs_to :user
  end

如您所见,我也有用户角色。

这是两种型号的注册表格。

  #user registration form
  <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
    ...
    <%= f.select :role, collection: User.roles.keys.last(2) %>
    <%= f.input :mobile_number, required: true, autofocus: true  %>
    ...
  <% end %>

  #profile registration form 
  <%= simple_form_for(@profile) do |f| %>
    ...
    <% if current_user.seller? %>
      <%= f.input :location, required: true %>
    <% else %>
      <%= f.input :company_code, required: true %>
    <% end %>
    ...
  <% end %>

问题

当当前用户是 seller 我需要验证 :location 的存在,当用户是 buyer 然后验证 :company_code 的存在。 我怎样才能做到这一点?感谢您的帮助,谢谢!

【问题讨论】:

  • location是profile表中的属性吗?
  • @Ahmadhamza nope 它的配置文件表属性

标签: ruby-on-rails ruby validation activerecord devise


【解决方案1】:

validates 方法接受if 选项:

# app/model/profile.rb
  class Profile < ApplicationRecord
    belongs_to :user    
    validates :location, presence: true, if: "user.seller?"
    validates :company_code, presence: true, if: "user.buyer?"
  end

另外,current_user.role == "seller" 已过时。 Rails 会自动在模型中为枚举选项值设置额外的方法,因此您可以只写:current_user.seller? 等。

【讨论】:

  • @arm2pro 欢迎您。如果我的回答解决了您的问题,请不要忘记将其标记为已接受
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多