ruby-on-railsarraysruby-on-rails-3model-view-controllercontroller-action

how to use array variables inside action in controller


I want to fetch all posts posted by those users who have gone to same college as the current users...So inside my welcome controller i have written following code..


class WelcomesController < ApplicationController

def index

  @col = Education.select(:college_id).where(:user_id => @current_user)
  @user = Education.select(:user_id).where(:college_id => @col)
  @welcome = Welcome.where(:user_id => @user)

end

end

Following is my shema code for welcome and education model:

create_table "welcomes", :force => true do |t|
    t.text     "message"
    t.integer  "user_id"
end

create_table "educations", :force => true do |t|
    t.integer  "college_id"
    t.integer  "user_id"
end

@col = Education.select(:college_id).where(:user_id => @current_user)....this line returns college ids associated with current logged in user.This is working perfectly on my console which is returning following output..

[#<Education college_id: 1>, #<Education college_id: 2>]

but i dont know how to use this output in my next line,so i have written this statement which should return all the users whose college id is the output of prevous statement

@user = Education.select(:user_id).where(:college_id => @col)

and my last line should return all the posts posted by those users whose ids are inside the @user array:

 @welcome = Welcome.where(:user_id => @user)

but this is not working.When i run my project i cant see any output on my page and on console i am getting following output : SELECT welcomes.* FROM welcomes WHERE (welcomes.user_id IN (NULL)) which means its not getting any user ids.. How can i solve this ...


Solution

  • You can try this:

    @col = Education.select(:college_id).where(:user_id => @current_user.id).all
    @users = Education.select(:user_id).where(:college_id => @col.collect(&:college_id)).all
    @welcome = Welcome.where(:user_id => @users.collect(&:user_id)).all