簡體   English   中英

在嵌套模型Rails 3.2中獲取屬性

[英]Getting attributes in nested model rails 3.2

我有兩個模型用戶和個人資料。
我想在用戶名中保存用戶名和密碼,在個人資料中保存其他用戶個人資料詳細信息。
現在,
用戶模型具有:

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_attributes]返回參數的視圖[:profile]
導致質量分配錯誤。怎么了?

你試過了嗎

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM