Rails saving many to many only saves one association - ruby-on-rails

I have the following relationship in my models:
class ClientProfile < ActiveRecord::Base
has_many :client_folders
has_many :folders, through: :client_folders
accepts_nested_attributes_for :folders
end
class Folder < ActiveRecord::Base
has_many :client_folders
has_many :client_profiles, through: :client_folders
end
class ClientFolder < ActiveRecord::Base
belongs_to :client_profile
belongs_to :folder
end
I have the relationships built up in controller:
#client_profile = ClientProfile.new
2.times do |i|
#folder = Folder.new(folder_name: "folder #{i}")
#client_profile.folders << #folder
end
I have the following fields_for associations created in view:
<%= form_for #client_profile do |f| %>
...
<%= f.fields_for :folders do |folder_builder| %>
<%= folder_builder.text_field :some_column %>
...
<% end %>
<% end %>
And the create action:
def create
#client_profile = ClientProfile.new client_profile_params
if #client_profile.save
...
else
...
end
end
When I save the association, it does create the client_profile as well as the two folders, and the join model ClientFolder is correctly created twice. However in both ClientFolders created, it only has the folder_id filled in. The client_profile_id is left null.
One solution I tried is adding the following to client_profile to ensure it saves the join model relation correctly:
def folders_attributes=(params)
if params["0"][:id].nil?
params.values.each do |v|
f = Folder.new v
self.folders << f
end
end
end
But this raises the following exception when saving:
NoMethodError - undefined method `each' for #<ClientFolder:0x007fd364743d78>:
activemodel (4.1.5) lib/active_model/attribute_methods.rb:435:in `method_missing'
activerecord (4.1.5) lib/active_record/attribute_methods.rb:208:in `method_missing'
activerecord (4.1.5) lib/active_record/autosave_association.rb:349:in `save_collection_association'
activerecord (4.1.5) lib/active_record/autosave_association.rb:186:in `block in add_autosave_association_callbacks'
activerecord (4.1.5) lib/active_record/autosave_association.rb:157:in `instance_eval'
activerecord (4.1.5) lib/active_record/autosave_association.rb:157:in `block in define_non_cyclic_method'
activesupport (4.1.5) lib/active_support/callbacks.rb:424:in `block in make_lambda'
activesupport (4.1.5) lib/active_support/callbacks.rb:221:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:221:in `block in halting_and_conditional'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `block in halting_and_conditional'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `block in halting_and_conditional'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:215:in `block in halting_and_conditional'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `run_callbacks'
activerecord (4.1.5) lib/active_record/callbacks.rb:306:in `_create_record'
activerecord (4.1.5) lib/active_record/timestamp.rb:57:in `_create_record'
activerecord (4.1.5) lib/active_record/persistence.rb:482:in `create_or_update'
activerecord (4.1.5) lib/active_record/callbacks.rb:302:in `block in create_or_update'
activesupport (4.1.5) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.5) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.5) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `call'
activesupport (4.1.5) lib/active_support/callbacks.rb:86:in `run_callbacks'
activerecord (4.1.5) lib/active_record/callbacks.rb:302:in `create_or_update'
activerecord (4.1.5) lib/active_record/persistence.rb:103:in `save'
activerecord (4.1.5) lib/active_record/validations.rb:51:in `save'
activerecord (4.1.5) lib/active_record/attribute_methods/dirty.rb:21:in `save'
activerecord (4.1.5) lib/active_record/transactions.rb:268:in `block (2 levels) in save'
activerecord (4.1.5) lib/active_record/transactions.rb:329:in `block in with_transaction_returning_status'
activerecord (4.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:201:in `block in transaction'
activerecord (4.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:209:in `within_new_transaction'
activerecord (4.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:201:in `transaction'
activerecord (4.1.5) lib/active_record/transactions.rb:208:in `transaction'
activerecord (4.1.5) lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
activerecord (4.1.5) lib/active_record/transactions.rb:268:in `block in save'
Someone else recommended to add the join model association:
accepts_nested_attributes_for :client_folders
But it doesn't make sense to do that, since I am not using client_folders at all in the form. When I use fields_for :folders in form, it should be intelligent enough to save the join model properly in create.
How can I resolve this issue?

I discovered the problem.
I had defined the relation twice in the model:
has_many :client_folders
has_one :client_folders, :class_name => 'ClientFolder', :foreign_key => :folder_id
When I removed that has_one, everything worked accordingly.

Related

undefined method `resource_type' for #<Pin:0x00007fbb13c4aa10> Did you mean? restore_text

I am trying to CRUD my rails app and I am stuck. The form displays at /pins/new but after hitting submit I run into this ERROR.
Let me know if more files are required to solve this. It is saying that there is an undefined method 'resource_type' but I don't have a method by that name and is where I am confused. Been stuck on this for a couple days. Have googled a bunch and tried out various solutions with no luck. Please help. I appreciate you.
Getting ERROR
undefined method `resource_type' for # Did you mean? restore_text!
Github can be found at https://github.com/dustin-longenecker/rails-pinning-app
The last commit is before adding the get / post routes for creating a new pin.
Pointed at pins_controller.rb LINE 21 in the #CREATE method
class PinsController < ApplicationController
def index
#pins = Pin.all
end
def show
#pin = Pin.find(params[:id])
end
def show_by_name
#pin = Pin.find_by_slug(params[:slug])
render :show
end
def new
#pin = Pin.new
end
def create
#pin = Pin.create(pin_params)
redirect :show
end
private
def pin_params
params.require(:pin).permit(:title, :url, :slug, :text, :category_id)
end
end
routes.rb
root 'pins#index'
#get "pins/name-:slug" => "pins#show_by_name"
get "pins/name-:slug" => "pins#show_by_name", as: 'pin_by_name'
resources :pins
get "library" => "pins#index"
get "/pins/new" => "pins#new"
post "/pins" => "pins#create"
new.html.erb
<%= form_for #pin do |f| %>
<div class="form-group">
<label for="pin_title">Title</label>
<%= f.text_field(:title, class: "form-control") %>
</div>
<div class="form-group">
<label for="pin_url">URL</label>
<%= f.url_field(:url, class: "form-control") %>
</div>
<div class="form-group">
<label for="pin_text">Description</label>
<%= f.text_area(:text, class: "form-control") %>
</div>
<div class="form-group">
<label for="pin_category_id">Category</label>
<%= f.collection_select(:category_id, Category.all, :id, :name, class: "form-control") %>
</div>
<div class="form-group">
<%= f.submit(class: "btn btn-default")%>
</div>
<% end %>
MODEL pin.rb
class Pin < ActiveRecord::Base
validates_presence_of :title, :url, :slug, :text, :resource_type
validates_uniqueness_of :slug
belongs_to :category
end
MODEL category.rb
class Category < ActiveRecord::Base
has_many :pins
end
Migration create_category.rb
class CreateCategories < ActiveRecord::Migration[4.2]
def change
create_table :categories do |t|
t.string :name
end
add_column :pins, :category_id, :integer, references: :categories
add_index :pins, :category_id
if Category.all.empty?
Category.create(name: "ruby")
Category.create(name: "rails")
Category.create(name: "unknown")
end
unknown_category = Category.find_by_name("unknown")
pins = Pin.where("category_id is null")
pins.each do |pin|
category = Category.find_by_name(pin.resource_type)
if category.present?
pin.category_id = category.id
else
pin.category_id = unknown_category.id
end
pin.save
end
if Pin.where("category_id is null").empty?
remove_column :pins, :resource_type
puts "MIGRATION SUCCESSFUL!"
puts "All your data has been migrated successfully."
else
puts "ERROR! Something went wrong - not all pins have been assigned a category Id."
end
end
end
ERROR STACK
activemodel (5.2.2) lib/active_model/attribute_methods.rb:430:in `method_missing'
activemodel (5.2.2) lib/active_model/validator.rb:150:in `block in validate'
activemodel (5.2.2) lib/active_model/validator.rb:149:in `each'
activemodel (5.2.2) lib/active_model/validator.rb:149:in `validate'
activesupport (5.2.2) lib/active_support/callbacks.rb:426:in `block in make_lambda'
activesupport (5.2.2) lib/active_support/callbacks.rb:198:in `block (2 levels) in halting'
activesupport (5.2.2) lib/active_support/callbacks.rb:606:in `block (2 levels) in default_terminator'
activesupport (5.2.2) lib/active_support/callbacks.rb:605:in `catch'
activesupport (5.2.2) lib/active_support/callbacks.rb:605:in `block in default_terminator'
activesupport (5.2.2) lib/active_support/callbacks.rb:199:in `block in halting'
activesupport (5.2.2) lib/active_support/callbacks.rb:513:in `block in invoke_before'
activesupport (5.2.2) lib/active_support/callbacks.rb:513:in `each'
activesupport (5.2.2) lib/active_support/callbacks.rb:513:in `invoke_before'
activesupport (5.2.2) lib/active_support/callbacks.rb:131:in `run_callbacks'
activesupport (5.2.2) lib/active_support/callbacks.rb:816:in `_run_validate_callbacks'
activemodel (5.2.2) lib/active_model/validations.rb:409:in `run_validations!'
activemodel (5.2.2) lib/active_model/validations/callbacks.rb:118:in `block in run_validations!'
activesupport (5.2.2) lib/active_support/callbacks.rb:98:in `run_callbacks'
activesupport (5.2.2) lib/active_support/callbacks.rb:816:in `_run_validation_callbacks'
activemodel (5.2.2) lib/active_model/validations/callbacks.rb:118:in `run_validations!'
activemodel (5.2.2) lib/active_model/validations.rb:339:in `valid?'
activerecord (5.2.2) lib/active_record/validations.rb:67:in `valid?'
activerecord (5.2.2) lib/active_record/validations.rb:84:in `perform_validations'
activerecord (5.2.2) lib/active_record/validations.rb:46:in `save'
activerecord (5.2.2) lib/active_record/transactions.rb:310:in `block (2 levels) in save'
activerecord (5.2.2) lib/active_record/transactions.rb:387:in `block in with_transaction_returning_status'
activerecord (5.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:259:in `block in transaction'
activerecord (5.2.2) lib/active_record/connection_adapters/abstract/transaction.rb:239:in `block in within_new_transaction'
/Users/dl/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/monitor.rb:230:in `mon_synchronize'
activerecord (5.2.2) lib/active_record/connection_adapters/abstract/transaction.rb:236:in `within_new_transaction'
activerecord (5.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:259:in `transaction'
activerecord (5.2.2) lib/active_record/transactions.rb:212:in `transaction'
activerecord (5.2.2) lib/active_record/transactions.rb:385:in `with_transaction_returning_status'
activerecord (5.2.2) lib/active_record/transactions.rb:310:in `block in save'
activerecord (5.2.2) lib/active_record/transactions.rb:325:in `rollback_active_record_state!'
activerecord (5.2.2) lib/active_record/transactions.rb:309:in `save'
activerecord (5.2.2) lib/active_record/suppressor.rb:44:in `save'
activerecord (5.2.2) lib/active_record/persistence.rb:36:in `create'
app/controllers/pins_controller.rb:21:in `create'
actionpack (5.2.2) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (5.2.2) lib/abstract_controller/base.rb:194:in `process_action'
actionpack (5.2.2) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.2.2) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (5.2.2) lib/active_support/callbacks.rb:132:in `run_callbacks'
actionpack (5.2.2) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (5.2.2) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (5.2.2) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
activesupport (5.2.2) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.2) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.2) lib/active_support/notifications.rb:168:in `instrument'
actionpack (5.2.2) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (5.2.2) lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
activerecord (5.2.2) lib/active_record/railties/controller_runtime.rb:24:in `process_action'
actionpack (5.2.2) lib/abstract_controller/base.rb:134:in `process'
actionview (5.2.2) lib/action_view/rendering.rb:32:in `process'
actionpack (5.2.2) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (5.2.2) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (5.2.2) lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
actionpack (5.2.2) lib/action_dispatch/routing/route_set.rb:34:in `serve'
actionpack (5.2.2) lib/action_dispatch/journey/router.rb:52:in `block in serve'
actionpack (5.2.2) lib/action_dispatch/journey/router.rb:35:in `each'
actionpack (5.2.2) lib/action_dispatch/journey/router.rb:35:in `serve'
actionpack (5.2.2) lib/action_dispatch/routing/route_set.rb:840:in `call'
rack (2.2.2) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.2.2) lib/rack/etag.rb:27:in `call'
rack (2.2.2) lib/rack/conditional_get.rb:40:in `call'
rack (2.2.2) lib/rack/head.rb:12:in `call'
actionpack (5.2.2) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.2.2) lib/rack/session/abstract/id.rb:266:in `context'
rack (2.2.2) lib/rack/session/abstract/id.rb:260:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/cookies.rb:670:in `call'
activerecord (5.2.2) lib/active_record/migration.rb:559:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (5.2.2) lib/active_support/callbacks.rb:98:in `run_callbacks'
actionpack (5.2.2) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
web-console (3.7.0) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.7.0) lib/web_console/middleware.rb:30:in `block in call'
web-console (3.7.0) lib/web_console/middleware.rb:20:in `catch'
web-console (3.7.0) lib/web_console/middleware.rb:20:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.2) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.2) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.2) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.2) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.2) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.2) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.2.2) lib/rack/method_override.rb:24:in `call'
rack (2.2.2) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.2) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.2) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.2.2) lib/rack/sendfile.rb:110:in `call'
railties (5.2.2) lib/rails/engine.rb:524:in `call'
puma (4.3.3) lib/puma/configuration.rb:228:in `call'
puma (4.3.3) lib/puma/server.rb:682:in `handle_request'
puma (4.3.3) lib/puma/server.rb:472:in `process_client'
puma (4.3.3) lib/puma/server.rb:328:in `block in run'
puma (4.3.3) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
You have a validation that references resource_type:
class Pin < ActiveRecord::Base
validates_presence_of :title, :url, :slug, :text, :resource_type # its right here!
validates_uniqueness_of :slug
belongs_to :category
end
If you actually meant to have it then you need to add the column to the database with a migration.
And that's not how you create a resource.
class PinsController < ApplicationController
# ...
# POST /pins
def create
#pin = Pin.new(pin_params)
if #pin.save
redirect_to #pin
else
render :new
end
end
# ...
end

Im having trouble with an name error in Ruby on rails. Getting uninitialized constant User::Authors

The following question is within Rails. When i go to localhost:3000/Api/v1/users, i get a Name error. uninitialized constant User::Authors. I can't find what the error is about. its pointing to my Users controller, index. As i will show below.
Error:
NameError in Api::V1::UsersController#index
uninitialized constant User::Authors
Extracted source (around line #8):
6 #users = User.all
7
8 render json: #users
9 end
10
11
# # GET /users/1
So as I will show below, this error doesn't make sense to me. I just dont see where its coming from:
My users controller:
class Api::V1::UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
# # GET /users
def index
#users = User.all
render json: #users
end
# # GET /users/1
def show
render json: #user
end
# POST /users
def create
#user = User.new(user_params)
if #user.save
render json: #user, status: :created, location: #user
else
render json: #user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if #user.update(user_params)
render json: #user
else
render json: #user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
#user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:name, :username, :password_digest)
end
end
Just in case im posting my Authors Controller as well.
Authors controller
class Api::V1::AuthorsController < ApplicationController
before_action :set_author, only: [:show, :update, :destroy]
# GET /authors
def index
#authors = Author.all
render json: #authors
end
# GET /authors/1
def show
render json: #author
end
# POST /authors
def create
#author = Author.new(author_params)
if #author.save
render json: #author, status: :created, location: #author
else
render json: #author.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /authors/1
def update
if #author.update(author_params)
render json: #author
else
render json: #author.errors, status: :unprocessable_entity
end
end
# DELETE /authors/1
def destroy
#author.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_author
#author = Author.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def author_params
params.require(:author).permit(:name)
end
end
My routes
Rails.application.routes.draw do
post "/api/v1/login", to: "sessions#create"
delete "/api/v1/logout", to: "sessions#destroy"
get "/api/v1/get_current_user", to: "sessions#get_current_user"
namespace :api do
namespace :v1 do
resources :comments
resources :genres
resources :authors
resources :books
resources :users do
resources :books, only: [:index]
end
end
end
end
If there is anything more i should show I can update the question.
Thank you in advance.
UPDATE:
I was asked to add full backtrace:
activerecord (6.0.2.1) lib/active_record/inheritance.rb:206:in `compute_type'
activerecord (6.0.2.1) lib/active_record/reflection.rb:422:in `compute_class'
activerecord (6.0.2.1) lib/active_record/reflection.rb:769:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/association.rb:137:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/collection_association.rb:35:in `reader'
activerecord (6.0.2.1) lib/active_record/associations/builder/association.rb:100:in `authors'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:397:in `read_attribute_for_serialization'
active_model_serializers (0.10.10) lib/active_model/serializer/reflection.rb:168:in `value'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:17:in `object'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:50:in `serializer_class'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:34:in `serializer'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:199:in `block (2 levels) in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `yield'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `block (2 levels) in associations'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `block in associations'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `block in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:194:in `object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:179:in `cache_read_multi'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:25:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/attributes.rb:14:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/base.rb:61:in `as_json'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:35:in `encode'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:22:in `encode'
activesupport (6.0.2.1) lib/active_support/core_ext/object/json.rb:42:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/serializable_resource.rb:10:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:71:in `block (3 levels) in notify'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:112:in `block in run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:24:in `block (3 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:81:in `block in notify_render'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:80:in `notify_render'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:23:in `block (2 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `block in tag_logger'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `tag_logger'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:22:in `block in instrument_rendering'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `instance_exec'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `block in run_callbacks'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:139:in `run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:70:in `block (2 levels) in notify'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:157:in `block in <module:Renderers>'
active_model_serializers (0.10.10) lib/action_controller/serialization.rb:72:in `block (2 levels) in <module:Serialization>'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:150:in `block in _render_to_body_with_renderer'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each_key'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:146:in `_render_to_body_with_renderer'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:142:in `render_to_body'
actionpack (6.0.2.1) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `block in ms'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `ms'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:85:in `cleanup_view_runtime'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:34:in `cleanup_view_runtime'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:43:in `render'
app/controllers/api/v1/users_controller.rb:8:in `index'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:136:in `process'
actionpack (6.0.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `each'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
rack (2.2.2) lib/rack/session/abstract/id.rb:266:in `context'
rack (2.2.2) lib/rack/session/abstract/id.rb:260:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/cookies.rb:648:in `call'
rack (2.2.2) lib/rack/etag.rb:27:in `call'
rack (2.2.2) lib/rack/conditional_get.rb:27:in `call'
rack (2.2.2) lib/rack/head.rb:12:in `call'
activerecord (6.0.2.1) lib/active_record/migration.rb:567:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.2.2) lib/rack/runtime.rb:22:in `call'
activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.2.2) lib/rack/sendfile.rb:110:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
rack-cors (1.1.1) lib/rack/cors.rb:100:in `call'
railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
puma (4.3.3) lib/puma/configuration.rb:228:in `call'
puma (4.3.3) lib/puma/server.rb:682:in `handle_request'
puma (4.3.3) lib/puma/server.rb:472:in `process_client'
puma (4.3.3) lib/puma/server.rb:328:in `block in run'
puma (4.3.3) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
ALSO MY MODELS. FOR THE MODELS IM ABOUT TO SHARE, THERE ARE MORE MODELS THAN THIS, BUT I GUESS THE RELEVANT ONES ARE USER AND AUTHER.
class User < ApplicationRecord
has_secure_password
has_many :books
has_many :authors, through: :books
has_many :genres, through: :books
has_many :comments
# has_many :comments, through: :books
validates :username, uniqueness: true
end
AND NOW FOR AUTHER
class Author < ApplicationRecord
has_many :books
has_many :genres, through: :books
end
Since it was correct, I can post it as a proper answer instead of a comment.
Since it seems like it's having problems to find the Author class, can you verify the file name of the Author class, just so it's not accidentally saved as app/models/authors.rb (plural instead of singular) or something. Also, try to explicitly say
has_many :authors, through: :books, class_name: '::Author'
in your User class, just to see if it can actually find it explicitly instead of inferred.
Just so it's known, the answer was posted in the comments by #DanneManne. Thank you!
-- Explicitly say has_many :authors, through: :books, class_name: '::Author' in your User class, just to see if it can actually find it explicitly instead of inferred.

Rails - undefined method `string' for #<Entry:0x00007f56a005c398> Did you mean? String

I'm writing a Application which has following Model Design.
Model A has_many bs
Model B belongs_to a
b is sigular an bs/BS is plural
a is singular and as/AS is plural
and I'm using an Admin-controller to define what the users can do
class Admin::BsController < ApplicationController
def create
#a = A.find(params[:a_id])
#b = #a.bs.create(entry_params)
redirect_to a_path(#a)
end
def new
#b = B.new
end
end
The form in the view is show.html.erb is generated like
<%= form_with(model: [:admin, #a,B.new ], local: true) do |f| %>
<%= end %>
Expected behavior
Tell us what should happen
The new DB-entry which belongs_to a should be created.
I get an error
NoMethodError in Admin::EntriesController#create
undefined method `string' for #<B:0x00007f93a8090450> Did you mean? String
Rails version: Rails 5.1.5
Ruby version: Ruby 2.5.0p0
UPDATE
The idea is that a user can create a list with an personalized ID (admin_key) like doodle
Model A is the list
Model B are the entries of A
And can share that entry with the public_key)
That runs!
The problem is to add new entries to the list
The admin controlls that only the owner-url can run CRUD function to the list
The schema file
ActiveRecord::Schema.define(version: 20161023094929) do
create_table "admin_lists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "entries", force: :cascade do |t|
t.string "title"
t.string "email"
t.string "description"
t.boolean "state"
t.integer "list_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["list_id"], name: "index_entries_on_list_id"
end
create_table "lists", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "email"
t.string "admin_key"
t.string "public_key"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "exp_date"
t.string "state"
end
end
The full stackstrace
activemodel (5.1.5) lib/active_model/attribute_methods.rb:432:in `method_missing'
activemodel (5.1.5) lib/active_model/validator.rb:148:in `block in validate'
activemodel (5.1.5) lib/active_model/validator.rb:147:in `each'
activemodel (5.1.5) lib/active_model/validator.rb:147:in `validate'
activesupport (5.1.5) lib/active_support/callbacks.rb:413:in `block in make_lambda'
activesupport (5.1.5) lib/active_support/callbacks.rb:197:in `block (2 levels) in halting'
activesupport (5.1.5) lib/active_support/callbacks.rb:601:in `block (2 levels) in default_terminator'
activesupport (5.1.5) lib/active_support/callbacks.rb:600:in `catch'
activesupport (5.1.5) lib/active_support/callbacks.rb:600:in `block in default_terminator'
activesupport (5.1.5) lib/active_support/callbacks.rb:198:in `block in halting'
activesupport (5.1.5) lib/active_support/callbacks.rb:507:in `block in invoke_before'
activesupport (5.1.5) lib/active_support/callbacks.rb:507:in `each'
activesupport (5.1.5) lib/active_support/callbacks.rb:507:in `invoke_before'
activesupport (5.1.5) lib/active_support/callbacks.rb:130:in `run_callbacks'
activesupport (5.1.5) lib/active_support/callbacks.rb:827:in `_run_validate_callbacks'
activemodel (5.1.5) lib/active_model/validations.rb:405:in `run_validations!'
activemodel (5.1.5) lib/active_model/validations/callbacks.rb:114:in `block in run_validations!'
activesupport (5.1.5) lib/active_support/callbacks.rb:97:in `run_callbacks'
activesupport (5.1.5) lib/active_support/callbacks.rb:827:in `_run_validation_callbacks'
activemodel (5.1.5) lib/active_model/validations/callbacks.rb:114:in `run_validations!'
activemodel (5.1.5) lib/active_model/validations.rb:335:in `valid?'
activerecord (5.1.5) lib/active_record/validations.rb:65:in `valid?'
activerecord (5.1.5) lib/active_record/validations.rb:82:in `perform_validations'
activerecord (5.1.5) lib/active_record/validations.rb:44:in `save'
activerecord (5.1.5) lib/active_record/attribute_methods/dirty.rb:35:in `save'
activerecord (5.1.5) lib/active_record/transactions.rb:308:in `block (2 levels) in save'
activerecord (5.1.5) lib/active_record/transactions.rb:384:in `block in with_transaction_returning_status'
activerecord (5.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:233:in `transaction'
activerecord (5.1.5) lib/active_record/transactions.rb:210:in `transaction'
activerecord (5.1.5) lib/active_record/transactions.rb:381:in `with_transaction_returning_status'
activerecord (5.1.5) lib/active_record/transactions.rb:308:in `block in save'
activerecord (5.1.5) lib/active_record/transactions.rb:323:in `rollback_active_record_state!'
activerecord (5.1.5) lib/active_record/transactions.rb:307:in `save'
activerecord (5.1.5) lib/active_record/suppressor.rb:42:in `save'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:371:in `insert_record'
activerecord (5.1.5) lib/active_record/associations/has_many_association.rb:34:in `insert_record'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:360:in `block (2 levels) in _create_record'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:447:in `replace_on_target'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:281:in `add_to_target'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:358:in `block in _create_record'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:129:in `block in transaction'
activerecord (5.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `block in transaction'
activerecord (5.1.5) lib/active_record/connection_adapters/abstract/transaction.rb:194:in `block in within_new_transaction'
/home/marcus/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
activerecord (5.1.5) lib/active_record/connection_adapters/abstract/transaction.rb:191:in `within_new_transaction'
activerecord (5.1.5) lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `transaction'
activerecord (5.1.5) lib/active_record/transactions.rb:210:in `transaction'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:128:in `transaction'
activerecord (5.1.5) lib/active_record/associations/collection_association.rb:357:in `_create_record'
activerecord (5.1.5) lib/active_record/associations/has_many_association.rb:121:in `_create_record'
activerecord (5.1.5) lib/active_record/associations/association.rb:196:in `create'
activerecord (5.1.5) lib/active_record/associations/collection_proxy.rb:347:in `create'
app/controllers/admin/entries_controller.rb:7:in `create'
actionpack (5.1.5) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
actionpack (5.1.5) lib/abstract_controller/base.rb:186:in `process_action'
actionpack (5.1.5) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.1.5) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (5.1.5) lib/active_support/callbacks.rb:131:in `run_callbacks'
actionpack (5.1.5) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (5.1.5) lib/action_controller/metal/rescue.rb:20:in `process_action'
actionpack (5.1.5) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (5.1.5) lib/active_support/notifications.rb:166:in `block in instrument'
activesupport (5.1.5) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.1.5) lib/active_support/notifications.rb:166:in `instrument'
actionpack (5.1.5) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (5.1.5) lib/action_controller/metal/params_wrapper.rb:252:in `process_action'
activerecord (5.1.5) lib/active_record/railties/controller_runtime.rb:22:in `process_action'
actionpack (5.1.5) lib/abstract_controller/base.rb:124:in `process'
actionview (5.1.5) lib/action_view/rendering.rb:30:in `process'
actionpack (5.1.5) lib/action_controller/metal.rb:189:in `dispatch'
actionpack (5.1.5) lib/action_controller/metal.rb:253:in `dispatch'
actionpack (5.1.5) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
actionpack (5.1.5) lib/action_dispatch/routing/route_set.rb:31:in `serve'
actionpack (5.1.5) lib/action_dispatch/journey/router.rb:50:in `block in serve'
actionpack (5.1.5) lib/action_dispatch/journey/router.rb:33:in `each'
actionpack (5.1.5) lib/action_dispatch/journey/router.rb:33:in `serve'
actionpack (5.1.5) lib/action_dispatch/routing/route_set.rb:844:in `call'
rack (2.0.4) lib/rack/etag.rb:25:in `call'
rack (2.0.4) lib/rack/conditional_get.rb:38:in `call'
rack (2.0.4) lib/rack/head.rb:12:in `call'
rack (2.0.4) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.4) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/cookies.rb:613:in `call'
activerecord (5.1.5) lib/active_record/migration.rb:556:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/callbacks.rb:26:in `block in call'
activesupport (5.1.5) lib/active_support/callbacks.rb:97:in `run_callbacks'
actionpack (5.1.5) lib/action_dispatch/middleware/callbacks.rb:24:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/debug_exceptions.rb:59:in `call'
web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.5.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.1.5) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.1.5) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/request_id.rb:25:in `call'
rack (2.0.4) lib/rack/method_override.rb:22:in `call'
rack (2.0.4) lib/rack/runtime.rb:22:in `call'
activesupport (5.1.5) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.5) lib/action_dispatch/middleware/static.rb:125:in `call'
rack (2.0.4) lib/rack/sendfile.rb:111:in `call'
railties (5.1.5) lib/rails/engine.rb:522:in `call'
puma (3.11.3) lib/puma/configuration.rb:225:in `call'
puma (3.11.3) lib/puma/server.rb:624:in `handle_request'
puma (3.11.3) lib/puma/server.rb:438:in `process_client'
puma (3.11.3) lib/puma/server.rb:302:in `block in run'
puma (3.11.3) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
models/wishlist.rb
#models/list.rb
class List < ApplicationRecord
has_many :entries
validates :email, presence: true
validates :admin_key, :uniqueness => true
before_create :create_admin_key
before_create :create_public_key
state_machine initial: :inactive do
event :activate do
transition :inactive => :active
end
event :deactivate do
transition :activate => :inactive
end
end
def create_admin_key
begin
self.admin_key = SecureRandom.urlsafe_base64(len=15)
end while self.class.exists?(admin_key: admin_key)
end
def create_public_key
begin
self.public_key = SecureRandom.urlsafe_base64(len=8)
end while self.class.exists?(public_key: public_key)
end
# defined the public_key as the link to navigate the wishlist
def to_param
admin_key
end
end
models/entry.rb
#models/entry.rb
class Entry < ApplicationRecord
belongs_to :wishlist, optional: true
*validates :string, :uniqueness => true
before_create :create_entry_key
def create_entry_key
begin
self.string = SecureRandom.urlsafe_base64(len=5)
* end while self.class.exists?(string: string)
end
end
I hope this help you. I dont't find the error.
The Bug is in the Model entry.rb. The valiation is the model is a template. here is the correct code.
The broken and fixed code is marked with an arrow. This was in question only string and no variables. In my case entry_key.
#models/entry.rb
class Entry < ApplicationRecord
belongs_to :wishlist, optional: true
before_create :create_entry_key
validates_presence_of :wishlist
validates :entry_key, :uniqueness => true # <-
def create_entry_key
begin
self.entry_key = SecureRandom.urlsafe_base64(len=5) # <-
end while self.class.exists?(entry_key: entry_key) # <-
end
end

undefined method `each' for "27":String

I'm trying to get a number of users to be registered in a team , I updated my code so that a team can get registered, however the following error shows up :
undefined method `each' for "27":String
NoMethodError in TeamsController#create
My code is as follows:
class Team<ActiveRecord::Base
belongs_to :league
belongs_to :seed
has_many :speakers do
def user(level="1")
find_by(level: level).user
end
end
end
my user model looks like this :
class User < ActiveRecord::Base
belongs_to :team
end
user model:
class User<ActiveRecord::Base
has_many :speaking_engagements, class_name: "Speaker"
has_many :teams , through: :speaking_engagements
end
speaker model:
class Speaker < ActiveRecord::Base
belongs_to :team
belongs_to :user
end
Team Controller:
class TeamsController<ApplicationController
def new
#seed=Seed.find_by_id(params[:seed_id])
#league=current_admin.league
#team=current_admin.league.teams.build(:seed_id=>#seed,:approved=>false)
#usernames= #mca.connections.connected.each do |x| x.user end
end
def create
#league=current_admin.league
**#team = #league.teams.build(team_params)** #problem appears to be here
if #team.save
flash[:notice] = "Team Request Sent!."
redirect_to '/'
else
flash[:error] = "Unable to request team."
redirect_to :back
end
end
form looks like:
<div class="panel-body">
<div class="container">
<%= form_for #team do |f| %>
<%= f.hidden_field :seed_id, :value => #seed.id %>
<%= f.hidden_field :league_id, :value => #league.id %>
<div class="row">
<!-- <div class="col-md-8"> -->
<div class="form-group">
<%= f.collection_select :speakers, #usernames,:user_id,:fullname, multiple:true %>
</div>
<!-- </div> -->
</div>
<div class="actions">
<%= f.submit "Create" , class:"btn btn-primary" %>
</div>
<% end %>
</div>
</div>
Speaker migration:
class CreateSpeekers < ActiveRecord::Migration
def change
create_table :speakers do |t|
t.integer :team_id
t.integer :user_id
t.integer :level
t.timestamps null: false
end
end
end
I've been stuck with this error for quite sometime now, I would much appreciate any help!
Full trace:
activerecord (4.2.0) lib/active_record/associations/collection_association.rb:355:in `replace'
activerecord (4.2.0) lib/active_record/associations/collection_association.rb:47:in `writer'
activerecord (4.2.0) lib/active_record/associations/builder/association.rb:123:in `speekers='
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `public_send'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:41:in `block in assign_attributes'
actionpack (4.2.0) lib/action_controller/metal/strong_parameters.rb:183:in `each_pair'
actionpack (4.2.0) lib/action_controller/metal/strong_parameters.rb:183:in `each_pair'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:35:in `assign_attributes'
activerecord (4.2.0) lib/active_record/core.rb:557:in `init_attributes'
activerecord (4.2.0) lib/active_record/core.rb:280:in `initialize'
activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
activerecord (4.2.0) lib/active_record/reflection.rb:131:in `build_association'
activerecord (4.2.0) lib/active_record/associations/association.rb:247:in `build_record'
activerecord (4.2.0) lib/active_record/associations/collection_association.rb:136:in `build'
activerecord (4.2.0) lib/active_record/associations/collection_proxy.rb:254:in `build'
app/controllers/teams_controller.rb:13:in `create'
actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.2.0) lib/abstract_controller/base.rb:198:in `process_action'
actionpack (4.2.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:92:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:92:in `_run_callbacks'
activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_process_action_callbacks'
activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (4.2.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
activesupport (4.2.0) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (4.2.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.2.0) lib/active_support/notifications.rb:164:in `instrument'
actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (4.2.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
activerecord (4.2.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (4.2.0) lib/abstract_controller/base.rb:137:in `process'
actionview (4.2.0) lib/action_view/rendering.rb:30:in `process'
actionpack (4.2.0) lib/action_controller/metal.rb:195:in `dispatch'
actionpack (4.2.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
actionpack (4.2.0) lib/action_controller/metal.rb:236:in `block in action'
actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:73:in `call'
actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:42:in `serve'
actionpack (4.2.0) lib/action_dispatch/journey/router.rb:43:in `block in serve'
actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:in `serve'
actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:802:in `call'
warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
warden (1.2.3) lib/warden/manager.rb:34:in `catch'
warden (1.2.3) lib/warden/manager.rb:34:in `call'
rack (1.6.4) lib/rack/etag.rb:24:in `call'
rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
rack (1.6.4) lib/rack/head.rb:13:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/flash.rb:260:in `call'
rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
activerecord (4.2.0) lib/active_record/query_cache.rb:36:in `call'
activerecord (4.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:647:in `call'
activerecord (4.2.0) lib/active_record/migration.rb:378:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.2.0) lib/active_support/callbacks.rb:88:in `call'
activesupport (4.2.0) lib/active_support/callbacks.rb:88:in `_run_callbacks'
activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_call_callbacks'
activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
web-console (2.2.1) lib/web_console/middleware.rb:39:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.2.0) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.2.0) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.2.0) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.2.0) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
rack (1.6.4) lib/rack/runtime.rb:18:in `call'
activesupport (4.2.0) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/static.rb:113:in `call'
rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
railties (4.2.0) lib/rails/engine.rb:518:in `call'
railties (4.2.0) lib/rails/application.rb:164:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
rack (1.6.4) lib/rack/content_length.rb:15:in `call'
rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
/home/shyam/.rbenv/versions/2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
/home/shyam/.rbenv/versions/2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
/home/shyam/.rbenv/versions/2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'
The problem is that "27" (a user id) is being assigned as the speakers association for a team. This is wrong. speakers should be assigned instances of Speaker.
Unfortunately it gets tough at this point.
What you really need to do is use nested attributes to build the desired speaker records, where each speaker is assign one of the selected user ids. There are many ways to approach this in the UI. There are many great examples of using nested attributes, including this Railscasts episode
has_many gives you a lot of interesting methods, including collection_singular_ids and collection_singular_ids=. The gist of which means you should be able to leverage that getter & setter in your form like this
<%= f.collection_select :speaker_ids, #usernames, :user_id, :fullname, multiple: true %>
i found the answer to my question, thanks to following #WizardOfOgz comment,
so i did the following:
in my teams_controller.rb added the following parameters as permitted :
params.require(:team).permit(:user_id, :league_id,:seed_id, :approved, :speakers_attributes=>[:team_id,:user_id])
end
then,
in my team.rb added the follwing :
accepts_nested_attributes_for :speakers
further, added nested attributes in the form for team:
(in app/views/teams/_form.html.rb )
<h2>Speakers</h2>
<%= f.fields_for :speakers do |ff| %>
<div>
<%= ff.collection_select :user_id, #usernames,:user_id,:fullname%>
</div>
<% end %>
also since I wanted 3 speakers, I created the following function in helpers/form_helpers:
module FormHelper
def setup_team(team)
3.times{
team.speakers.build
}
team
end
end
that solved it for me,
thanks to #WizardOfOgz and #RichPeck
also this one really really helped:
http://www.sitepoint.com/complex-rails-forms-with-nested-attributes/

ActiveRecord::ReadOnlyRecord Exception raised when parent is readonly

I have the following two models:
# app/models/customer.rb
class Customer < ActiveRecord::Base
has_paper_trail
serialize :mail_opt_out, Set
before_create :generate_token
has_many :wallets
has_many :tickets, through: :wallets
...
# We have a special seeded customer with id -1 that we don't want changing
def readonly?
persisted? && id < 0
end
end
# app/models/ticket.rb
class Ticket < ActiveRecord::Base
include SparkCast
has_paper_trail
belongs_to :price
belongs_to :basket
belongs_to :occurrence
has_one :event, through: :occurrence
has_one :wallet, through: :basket
has_one :basket_type, through: :basket
has_one :customer, through: :basket
delegate :id, to: :customer, allow_nil: true
...
def admit
ensure_can_admit
self.state = 'admitted'
self.save!
end
cast_on :admit, room: :admittance
def as_cast
{
id: id,
customer_id: customer_id
}
end
end
The relevant association is a little convoluted, but is customers -> wallets -> baskets -> tickets.
When I call admit on an instance of a ticket that belongs to our customer with id -1, (which is read only) I get an ActiveRecord::ReadOnlyRecord exception.
I'm confused as to what is causing this, as neither ticket nor customer have any before_update callbacks. If I change
has_one :customer, through: :basket
to
delegate :customer, to: :basket
then everything is fine. Something seems to be either trying to update the customer, or at least checking if it is readonly.
I've done a bit of stepping through the save procedure using byebug, but haven't been able to find anything useful.
What is likely to be checking if an associated model is readonly, and how do I get around this? Is using delegate the best option here?
Edited to add:
Also including SparkCast, which I had omitted previously. Removing the cast_on method from my ticket model is fixing the problem.
# app/models/concerns/spark_cast.rb
module SparkCast
extend ActiveSupport::Concern
module ClassMethods
def cast_on(*args)
# Options are the last argument.
options = args.pop
room = options[:room]
args.each do |operation|
class_eval do
begin
alias_method "#{operation}_without_cast", operation
define_method operation do |*args|
cast_hash = as_cast
...
send("#{operation}_without_cast", *args)
cast(room, operation, cast_hash)
end
rescue NameError => e
raise "#{e.name} has not been defined yet. Include cast_on after method definition"
end
end
end
end
end
end
Backtrace:
- activerecord (4.1.0) lib/active_record/persistence.rb:481:in `create_or_update'
- activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `block in create_or_update'
- activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
- activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `create_or_update'
- activerecord (4.1.0) lib/active_record/persistence.rb:103:in `save'
- activerecord (4.1.0) lib/active_record/validations.rb:51:in `save'
- activerecord (4.1.0) lib/active_record/attribute_methods/dirty.rb:21:in `save'
- activerecord (4.1.0) lib/active_record/transactions.rb:268:in `block (2 levels) in save'
- activerecord (4.1.0) lib/active_record/transactions.rb:329:in `block in with_transaction_returning_status'
- activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:209:in `transaction'
- activerecord (4.1.0) lib/active_record/transactions.rb:208:in `transaction'
- activerecord (4.1.0) lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
- activerecord (4.1.0) lib/active_record/transactions.rb:268:in `block in save'
- activerecord (4.1.0) lib/active_record/transactions.rb:283:in `rollback_active_record_state!'
- activerecord (4.1.0) lib/active_record/transactions.rb:267:in `save'
- activerecord (4.1.0) lib/active_record/autosave_association.rb:393:in `save_has_one_association'
- activerecord (4.1.0) lib/active_record/autosave_association.rb:188:in `block in add_autosave_association_callbacks'
- activesupport (4.1.0) lib/active_support/callbacks.rb:424:in `block in make_lambda'
- activesupport (4.1.0) lib/active_support/callbacks.rb:221:in `block in halting_and_conditional'
- activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
- activerecord (4.1.0) lib/active_record/callbacks.rb:310:in `update_record'
- activerecord (4.1.0) lib/active_record/timestamp.rb:70:in `update_record'
- activerecord (4.1.0) lib/active_record/persistence.rb:482:in `create_or_update'
- activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `block in create_or_update'
- activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
- activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
- activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `create_or_update'
- activerecord (4.1.0) lib/active_record/persistence.rb:125:in `save!'
- activerecord (4.1.0) lib/active_record/validations.rb:57:in `save!'
- activerecord (4.1.0) lib/active_record/attribute_methods/dirty.rb:29:in `save!'
- activerecord (4.1.0) lib/active_record/transactions.rb:273:in `block in save!'
- activerecord (4.1.0) lib/active_record/transactions.rb:329:in `block in with_transaction_returning_status'
- activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction'
- activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:219:in `within_new_transaction'
- activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction'
- activerecord (4.1.0) lib/active_record/transactions.rb:208:in `transaction'
- activerecord (4.1.0) lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
- activerecord (4.1.0) lib/active_record/transactions.rb:273:in `save!'
- () home/hayden/development/SparkSeat/api/app/models/ticket.rb:79:in `admit'

Resources