Saving an array of ids into a foreign key field - Rails 4

Hourglass

I'm having an issue with my ROR 4 application. Here's a quick background:

The application has several classes, Users, Training_Events and Mission_Notes.

A Training event can be associated with multiple users from a multi-select drop-down which builds an array of user_ids which are then saved to the Training_Event, whilst Mission_Notes can only be associated with one User and one Training_Event. Models below:

MissionNote.rb

 class MissionNote < ActiveRecord::Base
    belongs_to :training_event
    belongs_to :user
 end

User.rb

class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token, :reset_token
before_save   :downcase_email
before_create :create_activation_digest

belongs_to :group
has_many :ranks
has_many :mission_notes
has_and_belongs_to_many :training_events
validates :username, presence: true
validates :email, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
validates :group_id, presence: true
has_secure_password
validates :password, length: { minimum: 6 }, allow_blank: true
end

TrainingEvent.rb

class TrainingEvent < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :mission_notes



validates :title, presence: true
validates :date, presence: true
validates :mission, presence: true
validates_format_of :video, :with => /\A(https\:\/\/)?((www\.)?youtube\.com|youtu\.?be)\/.+$\Z/, :allow_blank => true, :message => "must be a valid YouTube URL"
validates_format_of :date, :with => /\A((19|20)\d\d+)-(0[1-9]|1[012]+)-(0[1-9]|[12][0-9]|3[01])\Z/

end

What I then want it to do is on the user's profile display a list of the events that the particular user has been associated with and the mission_notes for each event. The issue I have is when I save the training event the user_id field is not saved in the database however if I do TrainingEvent.all.each{|x| x.user_ids} then I get an array of the user_ids which were saved.

Can someone help point out what I am doing wrong here and maybe help clarify while the single user_id finds nothing but user_ids returns at least an array of items.

------------------- Edit ------------------------------------ Training_Events_Controller.rb

class TrainingEventsController < ApplicationController
  before_action :set_training_event, only: [:show, :edit, :update, :destroy]
  before_action :admin_user, only: [:new, :edit, :update]

  # GET /training_events
  # GET /training_events.json
  def index
    @training_events = TrainingEvent.all
  end

  # GET /training_events/1
  # GET /training_events/1.json
  def show
    @user_ids = @training_event.user_ids
    @user = User.find(@user_ids)
    @mission_notes = MissionNote.find_by(user_id: @user)
    byebug
  end

  # GET /training_events/new
  def new
    @training_event = TrainingEvent.new
    @user_options = User.all.map{|u| [ u.username, u.id ] }
  end

  # GET /training_events/1/edit
  def edit
     @user_options = User.all.map{|u| [ u.username, u.id ] }
  end

  # POST /training_events
  # POST /training_events.json
  def create
      @training_event = TrainingEvent.new(training_event_params)

      respond_to do |format|
        if @training_event.save
          format.html { redirect_to @training_event, notice: 'Training event was successfully created.' }
          format.json { render :show, status: :created, location: @training_event }
        else
          format.html { render :new }
          format.json { render json: @training_event.errors, status: :unprocessable_entity }
        end
      end
    end

# PATCH/PUT /training_events/1
# PATCH/PUT /training_events/1.json
 def update
 respond_to do |format|
   if @training_event.update(training_event_params)
     format.html { redirect_to @training_event, notice: 'Training event was successfully updated.' }
    format.json { render :show, status: :ok, location: @training_event }
  else
    format.html { render :edit }
    format.json { render json: @training_event.errors, status: :unprocessable_entity }
  end
end
end

# DELETE /training_events/1
# DELETE /training_events/1.json
def destroy
  @training_event.destroy
  respond_to do |format|
    format.html { redirect_to training_events_url, notice: 'Training event was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_training_event
    @training_event = TrainingEvent.find(params[:id])
  end

# Never trust parameters from the scary internet, only allow the white list through.
def training_event_params
  params.require(:training_event).permit(:title, :date, :training_objective, :mission, :video, :user_ids => [])

end
end

Also as an additional can someone suggest the best way to then put this on the view in the way I described above, I realise this part is a little vague but it has sent me round the bend as I seem to get a repeating list of events and notes. Will attach view code when I have second

David Hoelzer

Since you are using HABTM, you will not have an automatic attribute of "User_ID"... You will however have "user_ids" because you have told it that there is a join table describing a many to many relationship. I suspect that when you are saving the training event you are trying to update a "user_id" attribute.. You should instead be adding the current user_id to the user_ids array attribute that represents the relation. :)

Hope this helps!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Rails 4.2 foreign key

From Dev

JPA saving primary and foreign key together

From Dev

Send a jQuery array of ids to Rails 4

From Dev

How to make ARRAY field with foreign key constraint in SQLAlchemy?

From Dev

Django: Saving form with User as Foreign key

From Dev

Rails not saving model field

From Dev

Updating foreign key field in Django

From Dev

Creating and saving foreign key objects using a SlugRelatedField

From Dev

How can I associate "foreign key" ids of one index to the corresponding data of another index in Elasticsearch using Rails?

From Dev

Saving a model with a foreign key in django

From Dev

Hibernate Primary Foreign Key field

From Dev

Ecto relations, not inserting foreign key ids

From Dev

Rails 4 - Strong Params - white labelling foreign key

From Dev

Django: saving dynamic forms with foreign key

From Dev

Rails: Validating an array of ids

From Dev

Foreign key is null after saving objects

From Dev

Rails foreign key is is allways null after saving

From Dev

Send a jQuery array of ids to Rails 4

From Dev

Filtering in Slick with foreign key field

From Dev

Updating foreign key field in Django

From Dev

Saving and retrieving an Array in Rails

From Dev

Rails 4 updating field in devise registrations controller before saving user

From Dev

how to modify child/foreign key ids of existing records without saving them

From Dev

Saving a model with a foreign key in django

From Dev

Hibernate Primary Foreign Key field

From Dev

Foreign key validation in rails

From Dev

how to perform a search query of a foreign key field's attribute in rails?

From Dev

Saving two records in Rails at the same time where one has a foreign_key pointing to the other

From Dev

Foreign key not saving rails 5

Related Related

  1. 1

    Rails 4.2 foreign key

  2. 2

    JPA saving primary and foreign key together

  3. 3

    Send a jQuery array of ids to Rails 4

  4. 4

    How to make ARRAY field with foreign key constraint in SQLAlchemy?

  5. 5

    Django: Saving form with User as Foreign key

  6. 6

    Rails not saving model field

  7. 7

    Updating foreign key field in Django

  8. 8

    Creating and saving foreign key objects using a SlugRelatedField

  9. 9

    How can I associate "foreign key" ids of one index to the corresponding data of another index in Elasticsearch using Rails?

  10. 10

    Saving a model with a foreign key in django

  11. 11

    Hibernate Primary Foreign Key field

  12. 12

    Ecto relations, not inserting foreign key ids

  13. 13

    Rails 4 - Strong Params - white labelling foreign key

  14. 14

    Django: saving dynamic forms with foreign key

  15. 15

    Rails: Validating an array of ids

  16. 16

    Foreign key is null after saving objects

  17. 17

    Rails foreign key is is allways null after saving

  18. 18

    Send a jQuery array of ids to Rails 4

  19. 19

    Filtering in Slick with foreign key field

  20. 20

    Updating foreign key field in Django

  21. 21

    Saving and retrieving an Array in Rails

  22. 22

    Rails 4 updating field in devise registrations controller before saving user

  23. 23

    how to modify child/foreign key ids of existing records without saving them

  24. 24

    Saving a model with a foreign key in django

  25. 25

    Hibernate Primary Foreign Key field

  26. 26

    Foreign key validation in rails

  27. 27

    how to perform a search query of a foreign key field's attribute in rails?

  28. 28

    Saving two records in Rails at the same time where one has a foreign_key pointing to the other

  29. 29

    Foreign key not saving rails 5

HotTag

Archive