【问题标题】:Ruby on rails: fields_for do nothing if defined submodel_attributes=Ruby on rails:fields_for 如果定义了 submodel_attributes= 则什么也不做
【发布时间】:2010-06-26 15:12:05
【问题描述】:

我在 new.erb.html 中有这样的代码:

<% form_for(@ratification) do |f| %>
  <%= f.error_messages %>

  <% f.fields_for :user do |fhr| %>
    <p>
      <%= fhr.label :url %><br />
      <%= fhr.text_field_with_auto_complete :url %>
    </p>
  <% end %>
<% end %>  

如果我有空的 Ratification.rb 没关系,fields_for 工作正常。

但如果我写了:

class Ratification < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
end

class Ratification < ActiveRecord::Base
  belongs_to :user
  def user_attributes=(attr)
  ...
  end
end

f.fields_for 什么也没产生!为什么!?

导轨:2.3.8

自动完成插件:repeated_auto_complete

【问题讨论】:

  • 我已经编辑了我的答案...

标签: ruby-on-rails nested-forms nested-attributes fields-for


【解决方案1】:

只需在 f.fields_for 中的 = (EQUAL)

像这样:

<%= f.fields_for :user do |fhr| %>
    <p>
        <%= fhr.label :url %><br />
        <%= fhr.text_field_with_auto_complete :url %>
    </p>
<% end %>

obs:你必须在 Rails 3 中做同样的事情

【讨论】:

    【解决方案2】:

    我相信你需要在你的控制器中建立一个用户,比如

    # controller
    def new
       @ratification = Ratification.new
       @ratification.build_user
    end
    

    怎么样

    <% f.fields_for :user, @ratification.user do |fhr| %>
       # ...
    <% end %>
    

    ?

    我相信如果你使用

    <% f.fields_for :user do |fhr| %>
    

    您应该将@user 作为实例变量。但在你的情况下,你有@ratification.user

    【讨论】:

      【解决方案3】:

      您无法重新定义user_attributes,因为您将覆盖 ActiveRecord 为其指定的标准行为。如果仍然知道这一点,您需要重新定义 user_attributes 尝试使用 alias_method_chain

      【讨论】:

        【解决方案4】:

        你没有做错吗?如果 Ratification 属于一个用户,那么用户模型应该接受嵌套的属性来进行批准,而不是相反。

        因此,如果用户有很多批准,并且如果您想在一个表单中为用户提交多个批准,那么您将在用户模型中使用接受嵌套属性进行批准。

        你会在用户控制器的某个地方做

        @user = User.new
        2.times { @user.ratifications.build } # if you want to insert 2 at a time
        

        我尝试在控制台中做类似的事情:

        @user = User.new
        @user.ratifications.build # this works
        

        如果我这样做了

        @ratification = Ratification.new
        @ratification.user.build # this fails
        

        【讨论】:

          【解决方案5】:

          我刚刚遇到了同样的问题,并且能够解决它。问题是fields_for:user 作为参数,而参数应该是@ratification.user

          因此,替换

          <% f.fields_for :user do |fhr| %>
          

          <% f.fields_for @ratification.user do |fhr| %>
          

          就是这样。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-09-13
            • 1970-01-01
            • 2016-10-27
            • 2017-04-21
            • 1970-01-01
            • 2020-05-29
            • 2019-01-17
            相关资源
            最近更新 更多