We start an operation by making sure a customer has enough items with which to work. So we begin by collecting all their current items in an array:
@items = SOrder.where(:user_id => current_user.id).order("order")
Then we determine how many items they should have. If someone has a free account, they should have 5 items. If it is a paid account they should have 20 items:
if current_user.paid
should_have = 19 # one less than 20 because of 0 position in the array
else
should_have = 4
end
Then, in case we need to add blank records, we figure out where we should start:
if @items.empty?
start = 0
else
start = @items.length + 1
end
If the start is less than or equal to what someone should have, then we add blank records:
if start <= should_have
value = [start .. should_have].each do |v|
SOrder.create(:user_id => current_user.id, :order => v, :item_id => 0 )
end
@items = SOrder.where(:user_id => current_user.id).order("order") # reload array
end
The records that should be added are not showing up in the database.
Where is the error?
The error may come from calling
.lengthfrom an Arel object and not a record set.However, since you only need a count for the first query, I’d suggest using
.count. If I was writing this I’d do something like:In User model:
Better Yet
In User model:
In controller:
While I am sure that you have a good reason, I am questioning why blank items need to be in the database at all. And, if a after_create hook could be used here.