如何创建新用户同时在rails中创建帖子?

时间:2014-11-16 21:39:52

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

我有模特帖,现在我需要这个: 如果用户未在现场获得授权,请创建新的用户模型和新的帖子模型,并提供有关新帖子的订阅通知。 我做了以下: 在帖子/新

上创建新表单
<% resourse.posts.build %>
    <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
      <%= devise_error_messages! %>
        <%= f.email_field :email, placeholder: "E-mail" %>
        <%= f.password_field :password, placeholder: "password" %>
        <%= f.password_field :password_confirmation, placeholder: "password confirmation" %>
           <%= f.fields_for :posts do |form| %>
           <%= form.text_field :title %>
           <%= form.text_field :content %>
      <%= f.submit "Sign up and create post" %>
    <% end %>
    <%= render "devise/shared/links" %>

我也将嵌套的attribustes添加到用户模型

class User < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts
end

并创建注册控制器

class RegistrationsController < Devise::RegistrationsController 

  def new
    super
  end

  def create
    super
  end
etc

然后我改变路线

devise_for :users, controllers: { registrations: "registrations" } 

它的工作正常,但我不知道如何通过电子邮件向订阅者发送关于我网站上新帖子创建的通知? 如何在注册控制器上确定帖子嵌套属性,如

@post = ????

请帮忙!

1 个答案:

答案 0 :(得分:0)

def create
    build_resource(sign_up_params)
    resource_saved = resource.save
    yield resource if block_given?
    if resource_saved
        if resource.posts.present?
            @post = resource.posts.first
            flash[:success] = "F#ck off it's all"
            User.includes(:categories, :roles).references(:categories, :roles).where(categories: {id: @post.category_id}, roles: { id: 4 }).pluck(:email).each do |email|
                PostsMailer.delay.deliver_posts_register(email, @post)
            end
        end
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_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_flashing_format?
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      @validatable = devise_mapping.validatable?
      if @validatable
        @minimum_password_length = resource_class.password_length.min
      end
      respond_with resource
    end
  end