Rails find_by new column

278 views Asked by At

I am new to rails ,

I have added a new column “control_id” in a table users and same is added in model file under

attr_accessible :control_id

But when I use find_by_control_id(1) . I am getting undefined method error . Do I need to add the column any where else ?

code :

search_id = User.find_by_control_id(1).id

in the webhook i will get control_id , i need to use the control_id to find the id in users table

Thanks

2

There are 2 answers

5
Rajdeep Singh On

It looks like there's no user with control_id 1 present in your DB, that's why it's thowing undefined method id for nilClass error. You need to handle it in some way in your controller, like I am redirecting to root_path incase the query returns nil.

search_id = User.find_by_control_id(1).try(:id)
redirect_to root_path if search_id.nil?

Hope that helps!

0
Pav On

Wondering if where would work?

User.where(control_id: 3)

or

User.find_by(control_id: params[:control_id]) 

i.e User.find_by(control_id: 3)

You can always do user = User then pp user.methods This will show you all the available methods.