gpt4 book ai didi

ruby-on-rails - state_machine 中状态的命名范围

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:15 28 4
gpt4 key购买 nike

我使用 state_machine在我的 Rails 3.1 应用程序之一上使用 ActiveRecord。我发现访问具有不同状态的记录的语法很麻烦。是否可以将每个状态同时定义为作用域而不用手写作用域定义?

考虑以下示例:

class User < ActiveRecord:Base
state_machine :status, :initial => :foo do
state :foo
state :bar

# ...
end
end

# state_machine syntax:
User.with_status :foo
User.with_status :bar

# desired syntax:
User.foo
User.bar

最佳答案

我正在将以下内容添加到我的模型中:

state_machine.states.map do |state|
scope state.name, :conditions => { :state => state.name.to_s }
end

不确定您是否将此算作“手动编写范围定义?”

关于ruby-on-rails - state_machine 中状态的命名范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8199354/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com