2013-10-13 27 views
0

我嘗試訪問我的@user對象內的數組的第一個元素,並從該數組中獲取第一個對象 。我只是把它不工作。下面是代碼:訪問窗體內的對象 - Rails

所有你正在努力推動整個預訂對象進入該領域,這似乎是錯誤的
<%= form_for(@user) do |f| %> 
     <% if @user.errors.any? %> 
     <div id="error_explanation"> 
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2> 

      <ul> 
      <% @user.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
      <% end %> 
      </ul> 
     </div> 
     <% end %> 

     <% if params[:redirect_to] -%> 
     <%= hidden_field_tag 'redirect_to', params[:redirect_to] %> 
     <% end -%> 
#Thats not working 
     Last booking: <%= f.text_field Booking.where("user_id="+ @user.id+").order('start_date DESC').first%> 

    <% end %> 

回答

0

首先,可能你要像booking_date或類似這樣的一些東西特別有價值。

Booking.where(user_id: @user.id).order(:start_date).last.booking_date 

其次,您在那裏有語法錯誤,text_field方法需要用戶模型字段的名稱。如果您定義了has_many:預訂,那麼您應該使用fields_for。請記住,如果您使用form_for表單構建器您必須引用模型字段,如果您需要自定義使用text_field_tag來代替。

text_field_tag :booking, Booking.where(user_id: @user.id).order(:start_date).last.booking_date