Here is my User controller show action
def show
@public_groups = Group.public
@groups_member = @user.groups_as_member
@groups_as_owner = @user.groups_as_owner
@random_items = []
@assignments = []
unless @groups_member.nil?
until @random_items.count == 5 do
random_groups = @groups_member.sort_by{rand}.slice(0,5)
random_groups.each do |group|
assignments = Assignment.where(:group_id => group.id).limit(5).all
#assignments = Assignment.find_by开发者_开发问答_group_id(group.id)
y = Post.find_by_id(assignments.rand.post_id)
@random_items << y
end
end
end
end
I think it might be the way I am declaring the instance variable arrays @random_items
and @assignments
. I have no idea what the problem is though because my development and production servers don't give any compilation errors or anything.
When I comment out the big block of logic starting with the array declarations the site works.
I'd suggest you to perform a refactoring before you can find an error. Some principles before:
- Any dataflow is about model layer responsibility
- instance variables are use to share objects between ActionPack layers (controller and view)
- use object's attributes instead of instance variables to easy to test
- use associations and minimize Arel method and just find in controllers
With according to your code, it can be rewritten with:
# User model
def random_items
return unless groups_as_member
random_groups = groups_member.sort_by{rand}.slice(0,5)
random_groups.each do |group|
return if randorm_groups.length > 5
assignments = group.assignments.limit(5)
if y = Post.rand_by_post(assignments)
random_groups << y
end
end
return random_groups
end
# Post model
def self.rand_by_post(assignments)
find_by_id(assignments.rand.post_id)
end
Once you have the logic clear, you can find the bug and cover it with tests.
精彩评论