2014-06-23 58 views
0

我想讓用戶在註冊步驟中選擇服務(免費,標準,專業版)。保存與omniauth身份的關係

這裏是DB模式我的工作:

(用戶)1 --- N(認購)N - 1(服務)

在 「新用戶」 的形式我有爲了讓用戶看到自定義代碼選擇的服務:

身份/ new.hmtl.erb

<%= form_tag "/auth/identity/register", :html => {:role=>"form"} do %> 
    <div class="form-group"> 
    <label>Service</label> 
    <%= select("service", "service_id", @available_services, {:selected => params[:service_id]}, {class:"form-control"}) %> 
    </div> 
    <div class="form-group"> 
    <label>Name</label> 
     <%= text_field_tag :name, nil, class:"form-control" %> 
    <p class="help-block">Nome e cognome completo e corretto.</p> 
    </div> 
    <div class="form-group"> 
    <label>Email</label> 
    <%= text_field_tag :email, @identity.try(:email), class:"form-control" %> 
    </div> 
    <div class="form-group"> 
    <label>Password</label> 
     <%= password_field_tag :password, nil, class:"form-control"%> 
    </div> 
    <div class="form-group"> 
    <label>Password confirmation</label> 
     <%= password_field_tag :password_confirmation, nil, class:"form-control"%> 
    </div> 
    <%= submit_tag "Sign up",class:"btn btn-default" %> 
<% end %> 

identities_controller.rb

class IdentitiesController < ApplicationController 
    skip_before_filter :require_login 
    layout "static" 
    def new 
    @available_services = Service.all.where(:id => [1, 2, 3]).collect {|p| [ p.name, p.id ] } 
    @identity = env['omniauth.identity'] 
    end 
end 

現在,什麼是創建/保存用戶和新用戶和所選擇的預訂之間的關係呢?

回答

0

我解決了這個由...

添加一個隱藏字段的服務:

#identitiy.new.html 
    <%= hidden_field_tag :service_id, params[:service_id] %> 

編輯的omniauth初始化如下:

#omniauth.rb 
Rails.application.config.middleware.use OmniAuth::Builder do 
    provider :identity,:fields => [:service_id,:name,:email], on_failed_registration: lambda { |env| 
    IdentitiesController.action(:new).call(env) 
} 
end 

新增attr_accessor和after_create方法在身份模型中:

#identity.rb 
class Identity < OmniAuth::Identity::Models::ActiveRecord 
    attr_accessor :service_id 

    validates_presence_of :name 
    validates_uniqueness_of :email 
    #validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i 

    after_create :add_subscription 

    private 
    def add_subscription 
    Subscription.create(:user_id => self.id, :service_id => service_id.to_f) 
    end 

end 
相關問題