我有2张桌子: -user_activity:包含ID活动和ID用户 -activity:包含Id,Id用户等...
我想只显示2个表中的活动
有我的代码: -activities包含用户的所有活动 -usersactivities_id在一个选项卡中包含用户的所有user_activity(例如:10,2,3)
def fetch_maj_activities
user = current_user
activities = []
user.groups.each do |group|
activities << Activity.where(group: group)
end
usersactivities_id = current_user.user_activities.select('activity_id').map(&:activity_id).uniq
activities.each do |activity|
if usersactivities_id.include? activity.id
else
activities = activities.flatten.reject {|a| a.id == activity.id}
end
end
@all_activities = activities.flatten.sort_by(&:updated_at).reverse
respond_to do |format|
format.js
end
end
日志:
CACHE Activity Load (0.0ms) SELECT "activities".* FROM "activities" WHERE "activities"."group_id" = $1 LIMIT $2 [["group_id", 1], ["LIMIT", 11]]
↳ /home/benjamin/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0.rc1/lib/active_record/log_subscriber.rb:98
NoMethodError (undefined method `id' for #<ActiveRecord::Relation []>
Did you mean? ids):
app/controllers/activities_controller.rb:65:in `block in fetch_maj_activities'
app/controllers/activities_controller.rb:64:in `each'
app/controllers/activities_controller.rb:64:in `fetch_maj_activities'
答案 0 :(得分:0)
有答案,为我工作:)
def fetch_maj_activities
user = current_user
activities = []
usersactivities_id = current_user.user_activities.select('activity_id').map(&:activity_id).uniq
user.groups.each do |group|
activities << Activity.where(group: group)
end
usersactivities_id.each do |useractid|
activities.flatten.each do |act|
if act.id == useractid
activities = activities.reject {|a|a}
end
end
end
@all_activities = activities.flatten.sort_by(&:updated_at).reverse
respond_to do |format|
format.js {render :action => "fetch_activities"}
end
end