0

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
  • What version of Rails you are using? Commented Feb 26, 2020 at 11:41
  • attr_accessible has nothing to do with finders or declaring attributes - its an old and depreciated way of doing mass assignment protection. ActiveRecord generates dynamic finders based on the database schema. Commented Feb 26, 2020 at 11:45

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

5 Comments

I am using rails 3.2 , find_by(control_id: 1) is also throwing undefined method error
is there a way to use find_by_column_name?
Can you add code to show the full query you are writing?
added the code , i need to find the id using the control_id , then i will add the output id in another table
@Eswar it looks like there's no user with that particular control_id is present in DB. You need to handle it in the code. Check my updated answer.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.