2016-11-24 99 views
2

我試圖解決與條件關聯對象的驗證。驗證關聯對象(延遲驗證)

直到他是作者爲止,用戶不需要填寫author_bio。因此,應用程序需要確保,如果用戶已經創建了任何帖子,那麼作者無法創建帖子,如果沒有author_bioauthor_bio無法刪除。

class User < ApplicationRecord 
    has_many :posts, foreign_key: 'author_id', inverse_of: :author 

    validates :author_bio, presence: { if: :author? } 

    def author? 
    posts.any? 
    end 
end 

class Post < ApplicationRecord 
    belongs_to :author, class_name: 'User', inverse_of: :posts, required: true 
end 

不幸的是,這並不在創造新的崗位驗證作者:

user = User.first 
user.author_bio 
=> nil 

post = Post.new(author: user) 
post.valid? 
=> true 
post.save 
=> true 
post.save 
=> false 
post.valid? 
=> false 

那麼,怎樣才能防止我不author_bio創造的新職位由用戶?我可以在Post模型中添加第二個驗證,但這不是乾的。有沒有更好的解決方案?

回答

0

答案在這裏似乎是使用validates_associated一旦你有你的協會設置正確(包括inverse_of你有,但註明爲別人,在很多情況下軌想念他們或他們創造不正確地)

所以在此處調整類:

class User < ApplicationRecord 
    has_many :posts, foreign_key: 'author_id', inverse_of: :author 

    validates :author_bio, presence: { if: :author? } 

    def author? 
    posts.any? 
    end 
end 

class Post < ApplicationRecord 
    belongs_to :author, class_name: 'User', inverse_of: :posts 

    validates :author, presence: true             
    validates_associated :author 
end 

現在,當您嘗試運行你做了什麼之前:

user = User.first 
user.author_bio 
=> nil 

post = Post.new(author: user) 
post.valid? 
=> false 
post.save 
=> false 

不允許你保存,因爲author_bio是空

只有一點需要注意的還有樹立正確的關聯,否則軌感到困惑和User類跳過驗證,因爲它認爲的關係尚不存在。

注:我在軌移除從belongs_torequired: true因爲5是默認的,所以你也不會只在軌需要validates :author, presence: true 5.