使用Rails多态关联形成用户注册

时间:2013-03-16 23:26:10

标签: ruby-on-rails ruby polymorphic-associations

我在使用多态关联进行用户注册时遇到了问题。我想从多个多态关联模型中显示字段,但我不能。

模型类:

class User < ActiveRecord::Base
  devise ...

  belongs_to :userable, :polymorphic => true
end

class Advisor < ActiveRecord::Base
  has_one :user, :as => :userable
  attr_accessible :extra
  accepts_nested_attributes_for :user # Idon't know if it is ok
end
class AnotherKingOfUser < ActiveRecord::Base
  #the same..
end

我想为每个特定的用户类型创建一个控制器,所以:

class AdvisorsController < ApplicationController
  # GET /advisors/new
  # GET /advisors/new.json
  def new
    # Here is where I'm not sure about what I did. I tried all variants buy any works for me.
    @advisor = Advisor.new
    @advisor.build_user

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @advisor }
    end
  end
end

我的观点:

<%= form_for(@advisor) do |f| %>
  <% if @advisor.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@advisor.errors.count, "error") %> prohibited this advisor from being saved:</h2>

      <ul>
      <% @advisor.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

 <% #f.fields_for :user do |ff| %>
 <% f.fields_for :user_attributes, @advisor.user||User.new do |ff| %>

    <div class="field">
      <%= ff.label :email %><br />
      <%= ff.text_field :email %>
    </div>

    <div class="field">
      <%= ff.label :password %><br />
      <%= ff.text_field :password %>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :bio %><br />
    <%= f.text_field :bio %>
  </div>


  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

所以在我的浏览器中只显示“生物”字段,但不显示用户模型(设计)的扩展字段。

2 个答案:

答案 0 :(得分:1)

当你以这样的形式使用关联时(通常在你的情况下使用accepts_nested_attributes_for),你需要创建对象,以便它们显示在表单上。

这意味着,在这里,当rails构建你的表单时,它会查找@advisor.user的内容,这是空的,因为我想在你的控制器中你做了类似的事情

@advisor = Advisor.new

因此,如果您希望显示用户的字段,则需要build用户

@advisor = Advisor.new
@advisor.build_user # this will create a instance of User, but will not persist it

使用rails会在构建表单时找到用户,然后显示所需的字段。

我希望能回答你的问题。

答案 1 :(得分:1)

class Advisor < ActiveRecord::Base
  has_one :user, :as => :userable
  attr_accessible :extra, :user_attributes
  accepts_nested_attributes_for :user # its ok
end

class AdvisorsController < ApplicationController

  def new
    @advisor = Advisor.new
    # @advisor.build_user   # unnecessary

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @advisor }
    end
  end
end

# view
<%= form_for(@advisor) do |f| %>
  <%= f.fields_for :user_attributes, @advisor.user||User.new do |ff| %>
    <div class="field">
      <%= ff.label :email %><br />
      <%= ff.text_field :email %>
    </div>
    <div class="field">
      <%= ff.label :password %><br />
      <%= ff.text_field :password %>
    </div>
  <% end %>
    ...
<% end %>