简体   繁体   English

从Rails中的活动记录中获取特定的列值

[英]Fetch specific column value from active records in rails

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 我想从活动记录中获取特定的列值,我在视图中编写了sql查询,但未获取数据... 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 和new.html.page 在此处输入图片说明 here Pan Card number is not display 这里不显示Pan卡号

please help me i am new in ruby on rails and tell me where am i wrong and what is issue 请帮助我,我是红宝石的新手,告诉我我在哪里错了,什么是问题

You can use pluck for this, see http://apidock.com/rails/ActiveRecord/Calculations/pluck 您可以为此使用pluck,请参阅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: 当您不熟悉ror时,以下内容可帮助您前进:

Do write the ActiveRecord queries in Models only for faster query execution, not in view, controller etc. 请勿仅在Models中编写ActiveRecord查询,而是为了在视图,控制器等中更快地执行查询。

So in this cases try to have a class method like 'get_pan_number' at Model and use it in view. 因此,在这种情况下,请尝试在Model处使用“ get_pan_number”之类的类方法,然后在视图中使用它。

OfferLetter.rb 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 new.html.erb

<% pan_no = OfferLetter.get_pan_number(params[:userID]) %>
<%= f.text_field :pan_number, { value: pan_no, placeholder: 'COYP1234IN', class: 'form-control' } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM