我有Rails多態模型,我想根據關聯的類應用不同的驗證。如何根據多態關聯類型(Rails)應用不同的驗證規則?
3
A
回答
3
類名是在以下設置爲實例的_type
柱:
class Comment
belongs_to :commentable, :polymorphic => true
end
class Post
has_many :comments, :as => :commentable
end
評論類將有commentable_id
和commentable_type
領域。 commentable_type
是類名,commentable_id
是外鍵。如果通過特定的後留言評論要到驗證,你可以做這樣的事情:
validate :post_comments_are_long_enough
def post_comments_are_long_enough
if self.commentable_type == "Post" && self.body.size < 10
@errors.add_to_base "Comment should be 10 characters"
end
end
OR,我覺得這個比較好:
validates_length_of :body, :mimimum => 10, :if => :is_post?
def is_post?
self.commentable_type == "Post"
end
如果你有幾個驗證,我會推薦以下語法:
with_options :if => :is_post? do |o|
o.validates_length_of :body, :minimum => 10
o.validates_length_of :body, :maximum => 100
end
1
validates_associated方法是你所需要的。 您只需將此方法鏈接到多態模型,它將檢查相關模型是否有效。
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
validates_associated :commentable
end
class Post < ActiveRecord::Base
has_many :comments, as: commentable
validates_length_of :body, :minimum => 10
validates_length_of :body, :maximum => 100
end
+0
我得到這個錯誤undefined method'body 'for – 2017-11-08 17:05:39
+0
@KickButtowski也許是因爲你的模型沒有屬性'body'? – Guillaume 2017-11-29 16:27:06
相關問題
- 1. 驗證Rails中的多態關聯類型
- 2. Rails的驗證態關聯
- 3. 不同用戶類型的Rails關聯
- 4. Rails:多態關聯,不同的選項取決於類型?
- 5. 驗證多態關聯
- 6. Rails + PostgreSQL,根據rails驗證規則創建重複記錄
- 7. 如何在兩側實例化具有多態關聯/驗證的Rails模型?
- 8. 如何應用關聯規則
- 9. 驗證Rails中的關聯模型
- 10. Rails 3 - 如何跳過驗證規則?
- 11. Rails關聯 - 如何爲不同類型的用戶設置關聯?
- 12. Rails 3.2根據不同的型號進行驗證
- 13. Rails 3:將相同的驗證規則應用於多個表字段
- 14. 應用相同的驗證規則多個字段
- 15. Yii CValidator規則:如何驗證模型
- 16. 驗證多態關聯模型中的作用域唯一性
- 17. 根據用戶選擇存儲和驗證不同類型
- 18. 驗證多態關聯的唯一性
- 19. 根據規則動態地執行驗證
- 20. 不同的驗證規則JSF
- 21. 如何驗證關聯的模型?
- 22. 如何驗證關聯的模型ID?
- 23. 如何使用jQuery驗證具有多個驗證規則集
- 24. 跳過對rails中多態關聯的驗證
- 25. 將Sitecore驗證規則應用於字段類型?
- 26. Rails的多態關聯,二assoc命令類型的一類
- 27. 如何通過驗證規則的動態值類
- 28. Rails驗證除非關聯
- 29. Rails:驗證關聯數
- 30. 驗證應用程序塊的對象驗證不規則集
這是低劣的部分。無法從多態模型中訪問屬性。 「未定義的方法'itemable_type'爲#」 –
BlackTea
2010-07-10 13:44:16
生活將是完美的,否則...... :( – BlackTea 2010-07-10 13:50:13
如果您將上面的代碼直接寫入您的課程將會失敗,它只能用於實例,而不是類。將'define_method'代碼添加到實例方法中,並且它應該通過。 – 2010-07-10 14:53:50