rails has_one通过表单

时间:2016-06-04 17:49:12

标签: ruby-on-rails activerecord relationship

administrator.rb:

class Administrator < ActiveRecord::Base
    has_one :administrator_role, dependent: :destroy
    has_one :role, through: :administrator_role
end

role.rb:

class Role < ActiveRecord::Base
    has_many :administrator_roles
    has_many :administrators, through: :administrator_roles
end

administrator_role.rb:

class AdministratorRole < ActiveRecord::Base
    belongs_to :administrator
    belongs_to :role
end

为&#34; new&#34; action administrator_controller:

<%= form_for @administrator do |f| %>
  <%= render 'shared/errors', object: @administrator %>

  <div class="form-group">
    <%= f.label :role_id, "Роль:" %>
    <%= f.collection_select(:role_id, @roles, :id, :name) %>
  </div>
...
  <%= f.submit 'Save', class: 'btn btn-primary btn-lg' %>
<% end %>

administrator_controller.rb:

class AdministratorsController < ApplicationController
  def new
    @administrator = Administrator.new
    @roles = Role.all
  end

  def create
    @administrator = Administrator.new(administrators_params)
    if @administrator.save
      flash[:success] = "Account registered!"
      redirect_to root_path
    else
      render :new
    end
  end

...
  private

  def administrators_params
    params.require(:administrator).permit(:login, :password, :password_confirmation, :role_id)
  end
end

当您打开页面时会收到错误:

undefined method `role_id' for #<Administrator:0x007f6ffc859b48>
Did you mean?  role

如何解决?如果我将role_id放到一个角色,当你创建管理员时会得到错误:

ActiveRecord::AssociationTypeMismatch (Role(#69964494936160) expected, got String(#12025960)):

1 个答案:

答案 0 :(得分:3)

您必须重写以下表单:

<%= form_for @administrator do |f| %>
  <%= render 'shared/errors', object: @administrator %>

  <div class="form-group">
    <%= f.fields_for :role do |role_form| %
      <%= role_form.label :role_id, "Роль:" %>
      <%= role_form.select(:id, @roles.map { |role| [role.name, role.id] }) %>
    <% end %>
  </div>
...
  <%= f.submit 'Save', class: 'btn btn-primary btn-lg' %>
<% end %>

您还需要添加1行,以使嵌套表单逻辑为:

class Administrator < ActiveRecord::Base
    has_one :administrator_role, dependent: :destroy
    has_one :role, through: :administrator_role
    accepts_nested_attributes_for :role
end

并且还将控制器更改为:

class AdministratorsController < ApplicationController

  #....

  private

  def administrators_params
    params.require(:administrator).permit(
      :login, :password,
      :password_confirmation,
      role_attributes: [ :id ]
    )
  end
end

当您使用has_one关联时,您会获得以下方法,但不会获得association_id=,这就是错误所在。

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})