在设计注册期间通过记录元数据插入has_many

时间:2013-11-13 19:17:41

标签: ruby-on-rails devise ruby-on-rails-4 has-many-through

我想提前感谢你。 我一直在寻找互联网以获得答案,但找不到任何东西,所以这里提出问题。

我通过设计进行了用户注册过程,我已经自定义了注册。

 <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div><%= f.label :name %><br />
  <%= f.email_field :name, :autofocus => true %></div>

  <div><%= f.label :email %><br />
  <%= f.email_field :email, :autofocus => true %></div>

  <div><%= f.label :password %><br />
  <%= f.password_field :password %></div>

  <div><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></div>


<div>Teaching:<%= f.label :language_ids %><br />
<%= collection_select('user', 'language_ids', @languages, :id, :name, {}, {:included_blank => false,:multiple => true } ) %>
</div>

<div>Learning:<%= f.label :language_ids %><br />
<%= collection_select('user', 'language_ids', @languages, :id, :name, {}, {:included_blank => false,:multiple => true } ) %>
</div>

我的控制器目前看起来像这样

def create
    @languages = Language.all
    build_resource(sign_up_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

现在有一个字段,我必须设置为切换名为fluency的中间表/模型上的元数据标志。基本上,如果数据来自Learning multiselect,我需要将其设置为0,如果数据来自Teaching multiselect,则需要设置为1。目前它只是在不切换元数据的情况下插入它。

一直在寻找但却找不到任何东西。

谢谢!

1 个答案:

答案 0 :(得分:0)

我会在保存资源之前提取参数。然后,我将Fluency记录的创建和resource块中ActiveRecord::Base.transaction的保存包装起来,这样如果任何记录的持久化失败,它们都会回滚。

这样的事情:

  def create
    @languages = Language.all
    build_resource(sign_up_params)

    ActiveRecord::Base.transaction do
      create_fluency_records(sign_up_params[:fluency_fields]

      result = resource.save!
    end

    if result
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

请注意,您的表单必须更改为在请求参数中的“fluency_fields”哈希中传递“learning”和“teaching”值。