【问题标题】:Getting attributes in nested model rails 3.2在嵌套模型导轨 3.2 中获取属性
【发布时间】:2012-09-03 09:54:19
【问题描述】:

我有两个模型用户和个人资料。
我想将用户名和密码保存在用户和其他用户配置文件详细信息中 个人资料。
现在,
用户模型有:

has_one :profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password,:profile_attributes

配置文件模型有

 belongs_to :user
 attr_accessible :firstname, :lastname

用户控制器有

 def new
    @user = User.new
    @profileattr = @user.build_profile
  end

  def create
    @user = User.new(params[:user])

    if @user.save
      redirect_to root_url, :notice => "user created successfully!"
    else
      render "new"
    end
  end

new.html.erb 视图包含用户和个人资料的字段。
视图有:

<%= form_for @user do |f| %>
  <% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>

      </ul>
    </div>
  <% end %>


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


  <%= f.fields_for @profileattr do |pf|%>
  <p>
    <%= pf.label :firstname %><br />
    <%= pf.text_field :firstname %>
  </p>
  <p>
    <%= pf.label :lastname %><br />
    <%= pf.text_field :lastname %>
  </p>
  <% end %>

  <p class="button"><%= f.submit %></p>
<% end %>

但是,当我运行此 Web 应用程序时,它显示错误:

无法批量分配受保护的属性:配置文件

在调试时我发现用户的属性为:

 :email:abc@gmail.com
 :password:secret

 :profile
            ---:firstname:abc
            ---:lastname:xyz

所以,视图返回 params[:profile] 而不是预期的 params[:profile_attributes]
导致批量分配错误。那么出了什么问题?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord actioncontroller actionpack


    【解决方案1】:

    你试过了吗

      <%= f.fields_for :profile do |pf|%>
    

    ?

    【讨论】:

    • 显然是profile我刚改名为profileattr没有效果!
    • 不仅是我更改的名称 - 我使用的是符号,而您使用的是实例变量。
    • 是的,这行得通!但我必须在新操作中保留行`@profileattr = @user.build_profile`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多