0

I want to fetch a specific column value from active records, i wrote the sql query in view but I did not get the data... new.html.erb

 <%= f.text_field :pan_number, { value: OfferLetter.where(["candidate_id = (?)",params[:userID]]).select("pan_number").first, placeholder: 'COYP1234IN', class: 'form-control' } %>

then I got following result in my view

OfferLetter.where(["candidate_id = ?",17]).select("pan_number")


OfferLetter Load (0.3ms)  SELECT `offer_letters`.`pan_number` FROM `offer_letters` WHERE (candidate_id = 17)
=> #<ActiveRecord::Relation [#<OfferLetter id: nil, pan_number: "COPYD123IN">]>

and new.html.page enter image description here here Pan Card number is not display

please help me i am new in ruby on rails and tell me where am i wrong and what is issue

2
  • try this, <%= f.text_field :pan_number, { value: OfferLetter.where(["candidate_id = (?)",params[:userID]]).first.select("pan_number").first, placeholder: 'COYP1234IN', class: 'form-control' } %> Commented Sep 27, 2016 at 8:06
  • when we where clause we get a active::record::collection, try to get single record after where query like add .first to it Commented Sep 27, 2016 at 8:08

1 Answer 1

1

You can use pluck for this, see http://apidock.com/rails/ActiveRecord/Calculations/pluck

In your case try Following:

OfferLetter.where("candidate_id = ?", params[:userID]).pluck("pan_number").first

And

As you are new to ror, following is to help you with way ahead:

Do write the ActiveRecord queries in Models only for faster query execution, not in view, controller etc.

So in this cases try to have a class method like 'get_pan_number' at Model and use it in view.

OfferLetter.rb

def self.get_pan_number(cand_id)
 OfferLetter.where("candidate_id = ?", cand_id).pluck("pan_number").first
end

And in the view use it as follows:

new.html.erb

<% pan_no = OfferLetter.get_pan_number(params[:userID]) %>
<%= f.text_field :pan_number, { value: pan_no, placeholder: 'COYP1234IN', class: 'form-control' } %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.