user3763074
user3763074

Reputation: 353

Integrating user id into creation of a new object in an Activerecord database

Creating a simple flashcard app with a single has many, belongs to relationship:

card belongs_to :user user has_many :cards

Because of AR conventions, have set up a validation for user_id in the cards table to reflect the association:

create_table "cards", force: :cascade do |t| t.string "word_text", null: false t.string "meaning_text", null: false t.integer "user_id", null: false end

Now, running feature tests on the creation of a new flashcard, running into trouble because i don't know how to ensure that the user_id column in the newly created object gets filled in with user.id... tried adding this to my form, but nothing seems to work...

```

<%= form_for @card do |f| %>
   <%= f.label :word_text %>
   <%= f.text_field :word_text %>

  <%= f.label :meaning_text %>
  <%= f.text_field :meaning_text %>

  <%= f.label :user_id %>
  <%= f.number_field :user_id %>

<%= f.submit "Create" %>

```

I know that this is the error because when I enter @card.save! in rails console i get this error:

ActiveRecord::RecordInvalid: Validation failed: User can't be blank

If I'm signed in okay, should the user id be automatically used to create the new object?

Very new to rails and can't seem to decipher what's going on here. Any help would be much appreciated. Thanks!

Upvotes: 3

Views: 222

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

You probably have a create action like this in your CardsController:

def create
  card = Card.new(card_params)
  if card.save
    redirect_to some_path
  else
    redirect_to some_other_path
  end
end

You should append the user's id in this create action and not ask (neither add a hidden_field as suggested) for the user's id in the form.

def create
  card = Card.new(card_params.merge(user_id: current_user.id))
  if card.save
    redirect_to some_path
  else
    redirect_to some_other_path
  end
end

Upvotes: 2

Related Questions