ActiveRecord find and only return selected columns aligned with [:id]

妖精的绣舞 提交于 2019-12-24 17:08:28

问题


I have a set of data that is in two different tables. I want to join them up on my /show page in my ruby on rails app. In the controller, I have it set to find the date, set a variable, use that date to look through the other database to pull the needed information.

My controller looks like this:

  def show
    @ticket = Ticket.find(params[:id])
    @hellodate = Ticket.select(:date)
    @winnings = Winnings.find(:all, :conditions => {:date => @hellodate})

  respond_to do |format|
   format.html # show.html.erb
   format.json { render json: @ticket }
   end
 end

for my @winnings to work, I need it to pull the row that has the date that matches with the @ticket date. I am new to this world and would love any input / solutions because this isn't working. It should only show one @winnings but it shows multiple though only ONE date will eve match. Thanks!


回答1:


Your @hellodate is not what you think it is. This:

@hellodate = Ticket.select(:date)

will, more or less, give you the result of saying:

select "date" from "tickets"

so you'll get all Tickets but only the date columns will be pulled out of the database. Presumably you just want the date from @ticket:

@ticket   = Ticket.find(params[:id])
@winnings = Winnings.where(:date => @ticket.date)


来源:https://stackoverflow.com/questions/19107761/activerecord-find-and-only-return-selected-columns-aligned-with-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!