2

I've been playing with the models for a bit.

I am using devise

My schema:

  create_table "complaints", force: :cascade do |t|
    t.string   "title"
    t.text     "complaint_info"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.integer  "user_id"
  end

  add_index "complaints", ["user_id"], name: "index_complaints_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    ...
  end

Complaint model:

class Complaint < ActiveRecord::Base
  belongs_to :user

  validates :title, presence: true
end

Users model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :complaints
end

I was assuming this was the setup for rails to assume the current_user id goes inside the user_id but it's not storing it, I have to do it manually in the controller like this:

def create
    @complaint = Complaint.new(complaint_params) do |c|
      c.user_id = current_user.id
    end

    if @complaint.save
      redirect_to dashboard_complaint_path(@complaint)
    else
      render 'new'
    end
  end

private

  def complaint_params
    params.require(:complaint).permit(:title, :complaint_info)
  end

Is this the right way to do it? thanks.

Johhan Santana
  • 2,336
  • 5
  • 33
  • 61

1 Answers1

7

For Rails to automatically set the foreign key you need to create the new record through the parent records association.

@complaint = current_user.complaints.new(complaint_params)
Arctodus
  • 5,743
  • 3
  • 32
  • 44
  • this works. one of my co-workers said that `.build` would work too, what's the difference here? thanks! – Johhan Santana Apr 27 '15 at 15:34
  • also, is it necessary to have an index for user_id? – Johhan Santana Apr 27 '15 at 17:54
  • 1
    Check [this answer](http://stackoverflow.com/questions/4954313/build-vs-new-in-rails-3) for the difference between `new` and `build`. Adding indexes on foreign keys will improve performance but it's not really noticeable until you get thousands of records. – Arctodus Apr 27 '15 at 19:15