0

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

我有一个用户注册过程,通过设计我已经定制了注册看起来像这样。

 <%= 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

现在我必须设置一个字段来切换中间表/模型上的元数据标志,称为流利度。基本上,如果数据来自学习多选,我需要将其设置为 0,如果数据来自教学多选,我需要将其设置为 1。目前它只是插入它而不切换该元数据。

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

谢谢!

4

1 回答 1

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在请求参数中调用的哈希中传递“学习”和“教学”值。

于 2013-11-13T20:26:07.560 回答