Integrating User ID into New Object Creation in Activerecord Database

Making a simple flash card application with one of them has a lot, belongs to the ratio:

card belongs_to :user user has_many :cards

Due to AR conventions, set up a check for user_id in the map 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 do function tests when creating a new flash card, running into problems because I don't know how to ensure that the user_id column in the newly created object is populated with user.id ... tried to add this to my form but nothing works...

``,

<%= 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 this is a bug because when I go into @card.save!

rails console I get this error:

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

If I'm signed ok, should the custom id be automatically used to create a new entity?

Very new to rails and can't decipher what's going on here. Any help is appreciated. Thank!

+3


source to share


1 answer


You probably have an action create

like this in your CardController:

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

      



You should add the user id to this create action and not ask (do not add hidden_field

as suggested) for the user id on 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

      

+2


source







All Articles