Simple Form simple_fields_for仅显示最后一条记录

时间:2015-07-31 14:05:23

标签: ruby-on-rails ruby-on-rails-4 simple-form

我有一个嵌套的简单表单给edit用户。用户具有他/她可以更新的配置文件,并且新记录被写入profile表。

由于关系simple_fields_for

all会显示user的{​​{1}}个人资料记录。 但是,我想只在表单中显示最新的个人资料记录!我该如何实现?

user 1 to many profile records

2 个答案:

答案 0 :(得分:2)

稍晚,但接受的答案并非100%准确。 (这只是一个评论,但没有代表。)我会这样做:

假设你有

class User < ActiveRecord::Base
  has_many :profiles  
  ...
  def latest_profile
    profiles.order(...) # query to get whatever record it is you want
  end
end

你的simple_fields_for可以只是

<%= f.simple_fields_for :profiles, f.object.latest_profile do |p| %>

请注意:配置文件的复数形式,并且我们不需要使用附加的实例变量来混淆控制器,因为您可以访问表单中的对象。 (使用单数将会起作用我相信,但你不会使用以下形式获取params:profiles_attributes,这意味着更多的代码可以解释唯一的参数。)

答案 1 :(得分:0)

编辑操作:

   class user > ApplicationController
      ... 
      def edit
        @profile = @user.profile.order("saved DESC").first
      end
      ...
    end

工作表格:

<%= simple_form_for(@user) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :lang %>
    <%= f.input :firstname %>
    <%= f.input :lastname %>
    <%= f.input :email %>
    <%= f.input :born %>
    <%= f.input :gender %>
    <%= f.simple_fields_for :profile, @profile do |p| %> # the magic needed here
        <%= p.input :postal_code %>
        <%= p.input :core %>
        <%= p.input :daytime %>  
        <%= p.input :style %>
    <% end %>
    <% if @is_new %>
      <%= f.simple_fields_for :status do |s| %>
        <%= s.input :entered, as: :hidden, input_html: { value: Time.current } %>
      <% end %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
相关问题