rts213
rts213

Reputation: 33

how to save the user_id after using "create!" in rails 3?

I've recently updated my controller code to this for create

class MicropostsController < ApplicationController
  before_filter :signed_in_user

   def create
  @micropost = current_user.microposts.build(params[:micropost])


  if @micropost.review
      params[:micropost].delete :review
      @thread = Discussion.create!(params[:micropost])    
    else
      @micropost.save

    end
    redirect_to root_path
  end

When I use the above, it seems to work as the Discussion or the Micropost gets created. However, I believe that using "create!" does not save the user_id. When I view the Discussions, the user_id is nil. How can I save the user_id with whoever made the post?

Tables in schema.db

create_table "users", :force => true do |t|
    t.string    "name"
    t.string    "email"
    t.timestamp "created_at",                         :null => false
    t.timestamp "updated_at",                         :null => false
    t.string    "password_digest"
    t.string    "remember_token"
    t.boolean   "admin",           :default => false
  end




  create_table "discussions", :force => true do |t|
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

Upvotes: 1

Views: 525

Answers (2)

nzifnab
nzifnab

Reputation: 16092

Change

@thread = Discussion.create!(params[:micropost])   

To:

@thread = current_user.discussions.create(params[:micropost])

This will get you the user_id

However... I think your controller is trying to "do too much". If this is the create action for microposts Why would it create a discussion and not a micropost?

Also if there are validation errors in that @micropost.save the user won't get any feedback, it'll just fail silently. Same goes for the discussion create, you don't want them to get the generic http status 500 error page "Something went wrong" when the discussion fails validation when you use the create! method.

Upvotes: 0

Raindal
Raindal

Reputation: 3237

The create! method basically runs a new and then a save! throwing a validation exception if there is one.

When you write this:

@micropost = current_user.microposts.build(params[:micropost])

It initializes (normally) a new micropost with the current_user id as if you had run:

@micropost = Micropost.new(params[:micropost].merge(user_id: current_user.id))

And @micropost.save saves it... Which in short does exactly the same as your create! method.

In conclusion I think you should delete this line:

@micropost = Micropost.create!(params[:micropost])

Upvotes: 1

Related Questions