简体   繁体   中英

Rails 4 Devise Call Back on Registration

I have two models

User(id, name, is_host,....)

Host(id, name, user_id,...)

With the Association

User hasOne Host

I am using Devise for the User Registration. When a user wants to register as a Host i want to set is_host = 1 and create a row in Host with the name of the Host he provides in the Registration Form.

What i want to do?

  1. Allow Registration Form to accept Host details
  2. Create the association data when user selects register as host

Am trying to figure where i can write the logic based on what the user chooses to register as and then create the associated row in Host.

User From

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

  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name %>
  </div>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @validatable %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <% f.label :password_confirmation %><br />
    <% f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :is_host %><br />
    <%= radio_button("user", "is_host", true) %> Yes
    <br/>
    <%= radio_button("user", "is_host", false) %> No
  </div>

  <div class="actions">
    <%= f.submit "Signup" %>
  </div>
<% end %>

Simple way is to add an attr_accessor to the user model, eg

attr_accessor :host_name

And use this in the form as

= f.text_field :host_name

You can add an after_create callback in the model to save the host based upon the value of the radio button

after_create :create_user_host, if: Proc.new { |user| user.is_host }

def create_user_host
  self.create_host(name: host_name)  
end

or

You can use https://github.com/ryanb/nested_form gem to save the association directly. Just add

 accepts_nested_attributes_for :host

and in the form

= nested_form_for resource do |f|
  # code for user
  = f.fields_for :host do |host_f|
    = host_f.text_field :name

More details can be found in nested_form gem documentation.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM