Reputation: 343
I have a rails project here. In the controller, I have one method defined
single_output
, and if the url is like /single_output/1
, it will give me the info of person_id=1
and then I want to add another method group_output
in the same controller, but will need to call single_output
. Basically what I want it do is if url is like /group_output/1
, it will give me the info of group_id=1
which includes some person_id
and these person_id
will give me all their info.
My solution is this:
Controller:
def single_output
person_id = param[:person.id]
result = Person.where(:person_id => person_id)
end
def group_output
group_id = params[:group_id]
person_ids = Group.where(:group_id => group_id)
person_ids.each do |person_id|
output = get '/single_output/' + person_id
end
end
Route:
match "School/single_output/:person_id(.:format)" => "School#single_output"
match "School/group_output/:group_id(.:format)" => "School#group_output"
But seems like the get
method is not a good way to do this.
Or I come up with another idea:
redirect_to '/single_output/' + person_id
But it shows Render and/or redirect were called multiple times in this action.
Upvotes: 0
Views: 49
Reputation: 36880
The regular way to do this is to use another method.
def single_output
get_person(params[:person_id])
end
def group_output
group_id = params[:group_id]
person_ids = Group.where(:group_id => group_id)
person_ids.each do |person_id|
output = get_person(person_id)
end
end
private
def get_person(id)
Person.where(person_id: id)
end
But your code is unusual... I would expect person_ids
in the group_output
would be an array of Group
objects. Does a Group object has_many
people? And do you need an array or just the first matching Group object? In which case you would just need to do...
def single_output
get_person(params[:person_id])
end
def group_output
@group = Group.find_by(group_id: params[:group_id])
end
private
def get_person(id)
Person.find_by(person_id: id)
end
And in your output view you would just iterate through @group.people
which would be all people who belong to the group.
And finally, the rails convention is that a record id is just called id
not record_id
so in a standard rails app I'd expect it to be @group = Group.find_by(id: params[:group_id])
or even @group = Group.find(params[:group_id])
although this version will raise an exception if the group record is not found.
Upvotes: 1