has_many conditional validation

20 views
Skip to first unread message

tonym

unread,
Nov 22, 2012, 7:57:29 AM11/22/12
to hobo...@googlegroups.com
Hi all,

not specifically a Hobo thing, but I can't find a resolution on other forums...
I'm trying to validate that a field is not null, if a specific category has been picked from the has_many association.
Model speaks for itself (this is simplified, not all my code)...

  fields do
   food_range :text
   timestamps
  end

  has_many :categories, :through => :category_assignments, :accessible => true
  has_many :category_assignments, :dependent => :destroy

  validates :food_style, :presence => true, :if => "self.categories.include?(:id => 1)"

All I'm trying to do is check if :id => 1 is included in the list of categories.  This always returns false at the moment.

Any ideas?

Cheers, Anthony.


Bryan Larsen

unread,
Nov 23, 2012, 2:02:56 PM11/23/12
to hobo...@googlegroups.com
The if clause does conditional validation: the validation only runs
when the if clause is true; when the if clause is false the validation
isn't even checked. I don't think that's what you want.

You're probably best off with validates_each:

http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_each

You can then put your conditions inside the block and it should work
as you expect.

Bryan
> --
> You received this message because you are subscribed to the Google Groups
> "Hobo Users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/hobousers/-/MnwmPW_gHD8J.
> To post to this group, send email to hobo...@googlegroups.com.
> To unsubscribe from this group, send email to
> hobousers+...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/hobousers?hl=en.

kevinpfromnm

unread,
Nov 26, 2012, 10:05:23 PM11/26/12
to hobo...@googlegroups.com
Also, I'd guess that the categories.include? (id) is not what you want since it's an actual list of category models and a literal reading of the value passed would suggest it's comparing against hash { :id => 1 }, which would be false.  Perhaps category_ids.include? would be more to what you're after.
Reply all
Reply to author
Forward
0 new messages