Rails 4 & Devise - Generate a Welcome post when a new user registers

时间:2016-03-04 17:48:00

标签: ruby-on-rails-4 devise

I generate Devise controllers with:

$ bash <(curl -s https://raw.github.com/foohey/cdc/master/cdc.sh -L)

Following the instructions from here

In model/user.rb:

has_many :posts

accepts_nested_attributes_for :posts

In registrations_controller.rb I wrote:

  def create
    super
    @registration = Registration.new
    respond_to do |format|
      if @registration.save
        current_user.posts.create!(
            name: 'Sample Post', 
            body: '<p style="text-align: justify;"><span style="font-size:14px"><span style="font-family:times new roman,times,serif">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></span></p>'    
             )          
      else
        format.html { render :new }
      end
    end
  end

In routes:

devise_for :users, :controllers => { :registrations => "devise/registrations" }

I have also tried with:

def create
  super
  if @user.persisted?
      post  = @user.posts.build
      post.name = 'Welcome Post'
      post.body = '<p style="text-align: justify;"><span style="font-size:14px"><span style="font-family:times new roman,times,serif">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></span></p>'
      post.save    
  end
end 

But I can not generate the sample post, how i can to achieve?.

1 个答案:

答案 0 :(得分:0)

您没有将实际记录分配给用户,因此,在这种情况下,您应该尝试这样做:

def create
  super
  if @user.persisted?
      post  = @user.posts.create(name:'Sample Post',
                                 body: '<p style="text-align: justify;"><span style="font-size:14px"><span style="font-family:times new roman,times,serif">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></span></p>')
  end
end