简体   繁体   中英

validate_inclusion_of using a list from a database

Here is what I'm trying to do:

I have a rail model, let's call it Item. In the db I have a list of items. Therefore I can do a

item = Item.find(28)

and get an object representing the item found in the database.

Now, I also have another Model, let's say Order that needs to do a validate_inclusion_of for one of its fields, to see if the item name is in the Item database. Something like

validates: item_name, :presence => true
:inclusion => Item.all.name #get an array of all possible item names

Can this be done? What would be the nicest way of doing that?

Best Regards,

O.

Try this:

validates_inclusion_of :item_name, :in => Proc.new{Item.select(:name).map(&:name)}

UPDATE

this is a the full implementation:

rails new shop
cd shop
rails g model item name:string
rails g model order item_name:string
rake db:migrate

now in your order model:

class Order < ActiveRecord::Base
  attr_accessible :item_name
  validates_inclusion_of :item_name, :in => Proc.new{Item.select(:name).map(&:name)}
end

now we need to test this in console

rails c

and in console

Item.create(name: 'book')
o = Order.new
o.valid?
=> false
o.errors
=> @messages={:item_name=>["is not included in the list"]}
o.item_name = 'book'
o.valid?
=> true

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM