仅循环访问持久化对象



这是我创建显示的代码:

def create
@display = @department.displays.new(display_params)
@token = @display.build_token(value: (max_token + 1) , status: 0)
if @display.save
....
end

max_token是在显示令牌中查找最大数量的令牌而调用的方法。

def max_token
@tokens = @department.displays.map do |display|
display.token.value
end
@tokens.max
end

问题

我使用创建方法中的代码为部门创建了一个新显示。

@display = @department.displays.new(display_params)

但它尚未保存,因为@display.save仅在max_token方法之后调用。

但是当调用max_token方法时,代码

@tokens = @department.displays.map do |display|

还显示部门未保存的显示。

并且由于尚未设置显示的令牌,因此尚未保存,因此会抛出nil 值错误。

我的解决方案

这是我到目前为止尝试过的,但我想知道是否有更好的方法。

def max_token
@tokens = @department.displays.map do |display|
if display.token.nil?
display.token.value
else
0
end
end
@tokens.max
end

如果您不担心数据库层value的唯一性,您可以简单地过滤掉具有nil值的显示token

def max_token
@department.displays.where.not(token: nil).map do |display|
display.token.value
end.max
end

(这也是假设您实际上不需要将@tokens分配为max_token的副作用。

尝试先创建一个新的分隔Display,然后在调用max_token后将其分配给@department,这样新Display就不会包含在@department.displays.map

def create
@display = Displays.new(display_params)
@token = @display.build_token(value: (max_token + 1) , status: 0)
@department.displays << @display        
if @display.save
....
end

最新更新