【问题标题】:Two form values are not being saved没有保存两个表单值
【发布时间】:2011-05-17 22:22:43
【问题描述】:

我有这个注册与设计:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

  <p><%= f.label :email %><br />
  <%= f.email_field :email %></p>

  <p><%= f.label :password %><br />
  <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :profile, resource.build_profile do |t| %>
     <div class ="field">
        <%= t.label :type, "Are you an artist or listener?" %><br />
        <div>Artist: <%= t.radio_button :type, "Profile::Artist", :id => "artist_button" %></div>
        <div>Listener: <%= t.radio_button :type, "Profile::Listener", :id => "listener_button" %></div>
      </div>
  <% end %>

  <p class="before"><%= f.submit "Sign up", :id => "new_user_submit" %></p>
<% end %>

然后我有一些动态插入字段的 JQuery:

$("#artist_button").click(function() {
        if ($('input#user_name').parent().hasClass('field')){
            $('input#user_name').parent().remove();
        }
        $(".before").before('<div class="field"><label for="user_name">Artist or Band/Group Name</label><br><input id="user_name" name="user[name]" size="30" type="text"></div>');
    }); 

但是,嵌套在用户表单中的type 属性和动态插入的name 属性不会保存到数据库中。值被输入为空。

这是为什么?我该如何解决这个问题?

更新:

名称属性不是attr_accessible,这导致它没有保存到数据库中。但是,嵌套在用户表单中的 type 属性是attr_accessible,但仍未保存到数据库中。

【问题讨论】:

  • 实际提交了什么?您在开发日志的 params 中看到了什么?
  • 它在参数中,但我认为它们不是 attr_accessible... 会在配置文件模型中输入 go 吗?
  • 像@apneadiving 一样,我强烈怀疑您没有将这些属性标记为 attr_accessible。默认情况下,设计会保护用户模型上的所有属性,因此您需要使它们可访问。
  • 哦,所以名称不是 attr_accessible,并且使它如此固定以至于...但是类型是并且仍然是 attr_accessible 但它没有被保存到数据库中...可能与嵌套表单与设计相结合
  • 你有accepts_attributes_for :profile 吗?

标签: ruby-on-rails ruby ruby-on-rails-3 forms devise


【解决方案1】:

"type" 是一个用于单表继承的“神奇”ActiveRecord 列名,这意味着您刚刚受到约定优于配置的影响。您需要将“类型”列重命名为其他名称 - 我通常使用“种类”作为列名。

【讨论】:

    【解决方案2】:

    尝试放入你的用户模型:

    attr_accessible :profiles_attributes
    

    连同其余的设计attr_accessible(email,remeber_me,etc),不要删除你所拥有的!

    【讨论】:

      【解决方案3】:

      type 是一个关联吗?如果是这样,您也必须将:type_id 添加到attr_accessible

      【讨论】:

        【解决方案4】:

        你添加了吗

        accepts_nested_attributes_for :profile 
        

        在您的用户模型中?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-31
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          • 2012-02-09
          • 2021-08-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多