0

我在 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

自动完成插件:repeat_auto_complete

4

5 回答 5

4

只需在 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 中做同样的事情

于 2011-07-23T15:37:00.340 回答
0

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

于 2010-06-28T11:10:05.187 回答
0

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

因此,更换

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

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

而已。

于 2011-01-23T11:08:27.580 回答
0

你这样做没有错吗?如果 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
于 2010-06-29T10:12:09.077 回答
0

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

# 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.

于 2010-06-26T15:30:58.310 回答