I'm creating a polling system. I would like all options to be made unique, but only within their respective Poll
. I'm using a proc
to validate that they are not blank:
class Poll < ActiveRecord::Base
has_many :options
accepts_nested_attributes_for :options, reject_if: proc { |attributes| attributes['option'].blank? }
end
But I'm not sure how to validate their uniqueness. I tried doing it within the Option
model but it's not rejecting duplicate options created through the Poll
form's f.fields_for
:
class Option < ActiveRecord::Base
belongs_to :poll
validates_uniqueness_of :option, scope: :poll_id
end
Is it possible to do it with proc
?
对选项属性(例如validates_uniqueness_of :title, :other, scope: :poll_id
应用唯一性验证
You can pass any condition to that proc. So you could do query for that column and see whether any results are returned and reject if it they are.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.