1

My project is at this github: https://github.com/hoolahoop/RoR_Projects.

I have a project which has Users, Events, and a join table between the two tables. An event is owned by a user, with a foreign key on the event table. The join table allows many users to be guests for many events.

I'm trying to let owners of events add and delete multiple guests at a time. Below is the controller action code that throws the error when deleting rows from the join table. Ctrl + f "error thrown here" to see where the error is thrown.

def create
    Rails.logger.event.debug("===New Create===\n")
    @user_check = true;

    #@event = Event.new(event_params)
    @event = Event.new(event_user_params)

    @users = User.new

    @event.users.each do |user|
        user.password = SecureRandom.base64
        user.password_confirmation = user.password
        #test all saves here
        if(!user.try(:save))
            user_check = false;
        end
    end
    Rails.logger.event.debug("Can we save all users: #{@user_check}. If true, continue.")
    if(@user_check)
        #add all saves here
        #add all associations here
        @event.users.each do |user|
            @user_in_database = User.find_by email: user.email
            Rails.logger.event.debug("User in database check. Id: #{@user_in_database.id}. Email: #{@user_in_database.email}.")
            if (@user_in_database.nil?) # if user is not in the database (unique email check)
                # create a new user
                User.transaction do
                    user.save
                end
                Rails.logger.event.debug("User id check: #{@user}")
                @event_user = EventUser.new(user_id: user.id, event_id: params[:event_id])
                # create a new join table record
                EventUser.transaction do
                    @event_user.save
                end
            else
                @event_user_join = EventUser.find_by user_id: @user_in_database.id, event_id: params[:event_id]
                Rails.logger.event.debug("Is there a join on this event for this user?. Join object: #{@event_user_join}. If this is nil, no join exists.")
                if (@event_user_join.nil?)
                    @event_user = EventUser.new(user_id: @user_in_database.id, event_id: params[:event_id])
                    EventUser.transaction do
                        @event_user.save
                    end
                else
                    Rails.logger.event.debug("Join user_id: #{@event_user_join.user_id}. Join event_id: #{@event_user_join.event_id}.")
                    Rails.logger.event.debug("Try removing join.")
                    EventUser.transaction do
                        @event_user_join.delete
                    end
                    Rails.logger.event.debug("Removal success.")
                end
            end
        end
        Rails.logger.event.debug("===Redirect to Event Guests Page===\n")
        redirect_to event_display_path(params[:event_id])
    else
        render 'new'
        Rails.logger.event.debug("===Render New===\n")
    end
end

private
    def event_user_params
        #params.require(:user).permit(:first_name, :last_name, :email)
        params.require(:event).permit(users_attributes: [:id, :first_name, :last_name, :email, :_destroy])
    end

    def random_password
        random_pass = SecureRandom.base64

    end

Models:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :event_users
  has_many :events, through: :event_users
  #validation code...
end

class EventUser < ApplicationRecord
  belongs_to :event
  belongs_to :user
end

class Event < ApplicationRecord
  #belongs_to :user
  belongs_to :owner, class_name: "User", foreign_key: :user_id
  has_many :event_users
  has_many :users, through: :event_users

  accepts_nested_attributes_for :users
  #validation code...
end

Migrations:

class DeviseCreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
  end
end

class AddNamesToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :first_name, :string, null: false, default: ""
    add_column :users, :last_name, :string, null: false, default: ""
  end
end

class CreateEvents < ActiveRecord::Migration[5.1]
  def change
    create_table :events do |t|
      t.string :name,              null: false, default: ""
      t.text :description,         null: true
      t.integer :option,           null: false, default: 1
      t.string :street_address,    null: true
      t.integer :apartment_number, null: true
      t.string :city,              null: true
      t.date :date,                null: true
      t.time :time,                null: true
      t.string :password,          null: false, default: ""
      t.references :user, foreign_key: true
    end
  end
end

class CreateJoinTableEventUser < ActiveRecord::Migration[5.1]
  def change
    create_join_table :events, :users do |t|
      t.index [:event_id, :user_id]
      t.index [:user_id, :event_id]
    end
  end
end

class RenameTableEventsUsers < ActiveRecord::Migration[5.1]
  def change
    rename_table :events_users, :event_users
  end
end

Full error in command prompt:

app/controllers/users_controller.rb:21:in `create'
Started POST "/events/16/users" for 127.0.0.1 at 2018-03-05 10:06:40 -0500
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"ph5zsZQ0HhHt2NAsCtGFDUo/+PmlrQmKyeXt6dcQMnnXFVoEgeh4Srp+p0z0C8mtOhF6Uf48suCw+2YO72+bzw==", "event"=

{"users_attributes"=>{"0"=>{"first_name"=>"Test1", "last_name"=>"Test11", "email"=>"test1@test.com", "_destroy"=>"false", "id"=>"8"}, "1"=>{"first_na me"=>"Test4", "last_name"=>"Test44", "email"=>"test4@test.com", "_destroy"=>"false", "id"=>"11"}, "2"=>{"first_name"=>"Test5", "last_name"=>"Test55", "email"=>"test5@test.com", "_destroy"=>"false", "id"=>"12"}}}, "commit"=>"Save", "event_id"=>"16"}

Unpermitted parameter: :id
Unpermitted parameter: :id
Unpermitted parameter: :id

(0.0ms) begin transaction User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "test1@test.com"], ["LIMIT", 1]]
(0.0ms) rollback transaction
(0.0ms) begin transaction User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "test4@test.com"], ["LIMIT", 1]]
(0.0ms) rollback transaction
(0.0ms) begin transaction User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "test5@test.com"], ["LIMIT", 1]]
(0.0ms) rollback transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "test1@test.com"], ["LIMIT", 1]]
EventUser Load (0.0ms) SELECT "event_users".* FROM "event_users" WHERE "event_users"."user_id" = ? AND "event_users"."event_id" = ? LIMIT ? [["us er_id", 8], ["event_id", 16], ["LIMIT", 1]]
(0.0ms) begin transaction
(0.0ms) rollback transaction
Completed 401 Unauthorized in 441ms (ActiveRecord: 2.0ms)

NoMethodError (undefined method `to_sym' for nil:NilClass):

app/controllers/users_controller.rb:56:in block (2 levels) in create' app/controllers/users_controller.rb:54:inblock in create' app/controllers/users_controller.rb:34:in `create'

Full error on browser

NoMethodError in UsersController#create undefined method `to_sym' for nil:NilClass Extracted source (around line #65): 63 64 65 66 67 68

                    Rails.logger.event.debug("Try removing join.")
                    EventUser.transaction do
                        @event_user_join.delete
                    end
                    Rails.logger.event.debug("Removal success.")
                end

Rails.root: D:/Development/RoR_Projects/Maestro/blog

Application Trace | Framework Trace | Full Trace app/controllers/users_controller.rb:65:in block (2 levels) in create' app/controllers/users_controller.rb:64:inblock in create' app/controllers/users_controller.rb:39:in `create' Request Parameters:

{"utf8"=>"✓","authenticity_token"=>"HfCo+U+X7DtWUrCn/O2KFEkioGtXyut99NEsjUL08DBs+4FMWkuKYAH0x8cCN8a0OQwiwwxbUBeNz6dqeotZhg==",
"event"=>
{"id"=>"16",
"owner"=>"5",
"users_attributes"=>
{"0"=>{"first_name"=>"Test1", "last_name"=>"Test11", "email"=>"test1@test.com", "_destroy"=>"false", "id"=>"8"},
 "1"=>{"first_name"=>"Test4", "last_name"=>"Test44", "email"=>"test4@test.com", "_destroy"=>"false", "id"=>"11"},
 "2"=>{"first_name"=>"Test5", "last_name"=>"Test55", "email"=>"test5@test.com", "_destroy"=>"false", "id"=>"12"}}},
"commit"=>"Save",
"event_id"=>"16"}

Version information:

OS: Windows 7 Professional Service Pack 1

Ruby -v: ruby 2.4.3p205 (2017-12-14 revision 61247) [x64-mingw32]

Rails -v: Rails 5.1.4

Libraries: please check gemfile.

Related lib's to this problem include gem 'bcrypt', '~> 3.1.11', gem 'devise', and gem 'cocoon'.

Additional Information:

If you need any more information to help debug this problem, I will be happy to edit this post.

I don't know where the to_sys no method error is coming from. I've found a few places inside devise where it is used, but I'm having trouble deciphering why it's happening, and which exact place it's being used.

I'm using cocoon to generate multiple user fields on my form, and then trying to save them all. Perhaps I'm using cocoon incorrectly. The sample projects didn't seem to cover my use case of having a join table.

Devise github: https://github.com/plataformatec/devise Cocoon github: https://github.com/nathanvda/cocoon

Millar248
  • 403
  • 8
  • 18
  • What does your user_params method look like? – hashrocket Mar 05 '18 at 15:33
  • Edited to include the private functions. – Millar248 Mar 05 '18 at 15:44
  • Try adding :id to the event_user_params. – hashrocket Mar 05 '18 at 15:45
  • When I do that, I get a different error. On @event = Event.new(event_user_params), I get: Couldn't find User with ID=8 for Event with ID= . Not sure how to pass in Event ID inside the permit function. Question code edited to show this update. – Millar248 Mar 05 '18 at 15:49
  • What do your models and migrations look like? – hashrocket Mar 05 '18 at 15:59
  • Edited to include model relationships (validations left out). – Millar248 Mar 05 '18 at 15:59
  • Edited to include model migrations. – Millar248 Mar 05 '18 at 16:05
  • Do it you have an events migration? – hashrocket Mar 05 '18 at 16:05
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166259/discussion-between-millar248-and-hashrocket). – Millar248 Mar 05 '18 at 16:06
  • Did you check the [example project](https://github.com/nathanvda/cocoon_simple_form_demo) where I demonstrate either adding an existing person or creating a new one. Or checked the wiki page where this was described? https://github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms Sorry, did not read entire question yet :) (but I saw you did a whole lot of management where that is in general just not needed imho) – nathanvda Mar 06 '18 at 07:10
  • Hi Nathan. Yes I did check the example project. I have been using it to create my app. Unfortunately, my model doesn't exactly fit the model you use in your basic setup. The following SO question describes the type of model relationships that I want to use: https://stackoverflow.com/questions/4516416/belongs-to-and-has-many-to-the-same-model . – Millar248 Mar 06 '18 at 23:34
  • do you have any model without primary key, if so declare a primary inside your model using self.primary_key = :user_id, :event_id – chinna2580 Mar 31 '21 at 05:57
  • Hi @Chinna2580, thanks for the suggestion. Honestly, I haven't worked on this code in years now, and this was my first and last RoR project, so I am completely blanking on whether or not I had any of my models with no primary key. TBH, knowing the way I structure things now, I don't think it's likely that I would have a table with no primary key, but it could be. Maybe I'll take a look at this again, as I always wanted to finish my idea. – Millar248 Apr 01 '21 at 14:16

0 Answers0