Ruby 噢,当尝试创建一个模型并设置一个带有 id 的数组时出现未定义的方法异常
Ruby Ohm, undefined method exception when trying create a model setting an array with ids
我曾尝试在模型属性中设置一个带有 id 的数组,如 https://github.com/soveran/ohm#models 中所述,但出现异常。我的代码有什么问题?
型号
class Event < Ohm::Model
attribute :title
set :attendees, :User
end
测试
@fran = User.create(name: "Fran", email: 'fran@gmail.com')
@jose = User.create(name: "Jose", email: 'jose@hotmail.com')
event = Event.create(title: 'Party in Las Vegas', attendees: [@fran.id,@jose.id])
NoMethodError: undefined method `attendees=' for #<Event:0x000000020fb430>
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `block in update_attributes'
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `each'
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `update_attributes'
您需要使用 Set#add
方法才能工作,并且该方法只需要 1 个参数:
@fran = User.create(name: "Fran", email: 'fran@gmail.com')
@jose = User.create(name: "Jose", email: 'jose@hotmail.com')
event = Event.create(title: 'Party in Las Vegas')
event.attendees.add(@fran)
event.attendees.add(@jose)
如果这些是关联,那么我会看看 collections
我曾尝试在模型属性中设置一个带有 id 的数组,如 https://github.com/soveran/ohm#models 中所述,但出现异常。我的代码有什么问题?
型号
class Event < Ohm::Model
attribute :title
set :attendees, :User
end
测试
@fran = User.create(name: "Fran", email: 'fran@gmail.com')
@jose = User.create(name: "Jose", email: 'jose@hotmail.com')
event = Event.create(title: 'Party in Las Vegas', attendees: [@fran.id,@jose.id])
NoMethodError: undefined method `attendees=' for #<Event:0x000000020fb430>
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `block in update_attributes'
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `each'
/home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `update_attributes'
您需要使用 Set#add
方法才能工作,并且该方法只需要 1 个参数:
@fran = User.create(name: "Fran", email: 'fran@gmail.com')
@jose = User.create(name: "Jose", email: 'jose@hotmail.com')
event = Event.create(title: 'Party in Las Vegas')
event.attendees.add(@fran)
event.attendees.add(@jose)
如果这些是关联,那么我会看看 collections