0

I am creating this really simple app and i've never had a problem with this but i really dont know what is wrong here. I have an account model that the only attribute is a user_id.

When i create a user everying is ok, but im not being able to create an accout.

User model:

class User < ApplicationRecord
  has_many :accounts
end

Account Model:

class Account < ApplicationRecord
  belongs_to :user
  has_many :credit_cards
end

Schema:

create_table "accounts", force: :cascade do |t|
    t.bigint "user_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_accounts_on_user_id"
  end

create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

When i do

Account.create(user_id: User.first)

it just doenst create.

3
  • try : Account.create!(user_id: User.first), that will raise an exception if is anything wrong with the creation, at least you will have an error, add it to the question, and I think you will obtain an answer Commented Jan 10, 2021 at 15:58
  • Also I think you need to do something like: Account.create(user_id: User.first.id) Commented Jan 10, 2021 at 15:59
  • 1
    You could also do User.first.accounts.create Commented Jan 10, 2021 at 16:19

1 Answer 1

1

Try Account.create(user_id: User.first.id)

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, that was it! Or i could have done Account.create(user: User.first) I was mixing both
Or – shorter – Account.create(user: User.first).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.