2

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

2 Answers 2

1

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!

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

3 Comments

Afraid not the Training Event controller updates a field called user_ids, updated the question with my controller code
It's not clear to me what you disagree with here. In your original question you made it sound as though were accessing user_id directly on the TrainingEvent model.
Sorry I should've been clearer, I've already implemented the change you suggested before I posted the question, the issue I am having is now finding results based on the user_id
0

The model TrainingEvent has the attribute user_ids which i assume is an array instead of user_id. What I suggest is receive the array of user_ids not saved but accessed using attr_accessor :user_ids then on creating Training Events, iterate through the user_ids and save each TrainingEvent with the respective user_id.

Make sure user_id is an attribute and not user_ids.

2 Comments

Just to check, wouldn't saving each TrainingEvent result in multiple events with the same name?
@Hourglass, yes... i overlooked that. Look like you got an answer

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.