Rails has_many通过simple_form设计注册

时间:2014-04-24 18:35:52

标签: ruby-on-rails ruby ruby-on-rails-4 devise

好的,我有一个用户:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :user_positions
  has_many :positions, :through => :user_positions
  accepts_nested_attributes_for :positions
end

此用户可以拥有多个位置:

class Position < ActiveRecord::Base
  has_many :user_positions
  has_many :users, :through => :user_positions
end

通过user_positions:

class UserPosition < ActiveRecord::Base
  belongs_to :user
  belongs_to :position
  accepts_nested_attributes_for :position
end

我有一个表单将所有这些位置显示为复选框:

  <%= simple_form_for resource, as: resource_name, url: registration_path(resource_name) do |f| %>
    <%= devise_error_messages! %>
      <%= f.label :email %>
      <%= f.email_field :email, autofocus: true %>
      <%= f.label :password %>
      <%= f.password_field :password, autocomplete: "off" %>
      <%= f.label :password_confirmation %>
      <%= f.password_field :password_confirmation, autocomplete: "off" %>
      <%= f.association :positions, as: :check_boxes %>
      <%= f.submit "Sign up", class: "button" %>
      <%- if controller_name != 'sessions' %>
        or
        <%= link_to "Sign in", new_session_path(resource_name), class: "button" %>
      <% end -%>
  <% end %>

我正在使用设计来处理注册,只有以下覆盖:

class RegistrationsController < Devise::RegistrationsController
  before_filter :configure_permitted_parameters, :only => [:create]

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :position_ids) }
  end

end

我通过从本网站挑选许多答案来构建这个......但由于某种原因,它仍然没有保存位置。我不确定我应该做什么。提前谢谢。

1 个答案:

答案 0 :(得分:1)

由于position_ids将作为数组传递,您需要更新configure_permitted_parameters,如下所示:

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :position_ids => []) }
  end