Rails:验证多对多关系中关联的存在

时间:2016-05-28 14:33:44

标签: ruby-on-rails ruby ruby-on-rails-4

我正在尝试验证User类中客户端的存在,但它似乎无法正常工作。它永远不会过去。我想创建具有许多客户端的用户:

 class User < ActiveRecord::Base

 has_many :client_users, dependent: :destroy
 has_many :clients, through: :client_users
 accepts_nested_attributes_for :client_users


 validates_presence_of :name
 validates_presence_of :clients


 end

.....

class ClientUser < ActiveRecord::Base

belongs_to :client
belongs_to :user

validates_presence_of :client
validates_presence_of :user

accepts_nested_attributes_for :user
accepts_nested_attributes_for :client

self.table_name = "clients_users"

end

.....

class Client < ActiveRecord::Base
has_many :person_contacts

has_many :users, through: :client_users
has_many :client_users, dependent: :destroy

has_many :cases, through: :client_cases
has_many :client_cases, dependent: :destroy

accepts_nested_attributes_for :client_users, :person_contacts,  allow_destroy: true

validates_presence_of :name

end

...

观点的一部分:

= fields_for :clients do |c|
        = c.select :id, Client.all.collect { |c| [c.name, c.id] }, {},  class: "select2-multiple user-clients form-control", multiple: "multiple"

和用户控制器处理的参数:

Parameters: {"utf8"=>"✓",   "authenticity_token"=>"d33YuCerXTEATlX4toVA==", "user"=>{"name"=>"", "surname"=>"", "email"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "address_city"=>"", "address_street"=>"", "address_house_number"=>"", "address_local_number"=>"", "address_postal_code"=>"", "address_postal_code_place"=>"", "phone"=>"", "role_id"=>"4"}, "clients"=>{"id"=>["", "2"]}, "commit"=>"Utwórz użytkownika"}

一切都运行良好,没有验证,但我需要确保用户以用户形式传递客户端

1 个答案:

答案 0 :(得分:0)

使用自定义验证

validate :has_clients

def has_clients
     errors.add(:base,  "There have to be clients") unless clients.size > 0
end