Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Find By Field other than ID

Ok again forget my noobiness in Rails, but I'm not finding this either. Although I think this one might be because well.. it doesn't exist?

Ok so I'm still playing with RoR and I added a controller for employee, pretty simple just a name, clock_no, and wage. But what if I don't want to search for an employee by ID? To me it would be easier for the user to search by clock number, but I'm not figuring out how that works. I am assuming it has something to do with this line, more specificly the set_employee line:

private
# Use callbacks to share common setup or constraints between actions.
def set_employee
  @employee = Employee.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
  params.require(:employee).permit(:name, :clock_no, :wage)
end

However I could be way off.

Ok so my solution ended up being just to change the primary_key in the model:

self.primary_key = 'clock_no'

And setting the return to json:

def show
@employee = Employee.find(params[:id])
 respond_to do |format|
   format.html
   format.json { render json: @employee }
 end
end

HOWEVER, I don't think this is really the end all solution, again my noobiness could be showing, but it seems kinda hockie to me. My hold up would be what if you wanted to search by say name or something else that wasn't the primary key and was not able to change the primary key like in my case? nose back to the docs

like image 877
tattooedgeek Avatar asked Jul 19 '13 21:07

tattooedgeek


2 Answers

Use where:

Employee.where(clock_no: params[:clock_no])

where returns an ActiveRecord relation, so if you need the first (and probably only instance if clock_no is unique), use first, like this:

Employee.where(clock_no: params[:clock_no]).first

This will execute only one SQL query to get the first Employee matching clock_no.

There used to be magic finders like find_by_clock_no, but those are deprecated as of Rails 4, which I assume you're using.

Also see the Rails documentation for more info on ActiveRecord queries.

like image 167
fivedigit Avatar answered Nov 15 '22 20:11

fivedigit


Try using a dynamic attribute-based finder, like so:

    Employee.find_by_clock_no(params[:clock_no])

check the docs for more info.

like image 41
Matt Kosoy Avatar answered Nov 15 '22 19:11

Matt Kosoy