Domanda

Hello people of stack overflow

I am relatively new to the rails platform and needed some help with model querying

Here is my code:

def create
@project = Project.new(params[:project])
if @project.save
    redirect_to new_project_path
end

student=@project.student_str.split(";")
end

Each time a new project is created, a string called student_str is stored, where the ID number of each student is seperated by a ";". I split that string to an array using the split function

So, here is my problem

I have another model called users which contains the list of all students in the system. I want to select @users for all the model entries where their ID matches any of the array values in the array "student".

Any help will be much appreciated

Thanks

EDIT:

Right now, I'm testing out with junk data.So my student_str would be something like 1PI12CS019;1PI10IS034;1PI11ME110

Each of the ID's are seperated by a ";"

The student model is created using the devise gem and contains the following fields

ID Name Email phone number

and the other devise stuff

È stato utile?

Soluzione

given student_str to be 1PI12CS019;1PI10IS034;1PI11ME110, the easiest way to fetch users with those ids is to split the string first and query using the result.

>> student_str = '1PI12CS019;1PI10IS034;1PI11ME110'
>> ids = student_str.split(';')
>> User.where(id: ids) # should give you a list of users matching the ids in the string

Knowing this, there are actually 2 things I'd like to bring up.

  1. you'll have an easier life using Rails if you stick to convention so I suggest you use integers as ids instead of those strings.
  2. instead of saving the ids in a single column, you're better off with creating another table that will associate users and students. Easiest way to do this is via has_and_belongs_to_many. A more complex approach would be to use has_many through. A quick google search for this should give you good results.

Good luck!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top