I'm trying a query to get the user that created a message in a specific sala but I can't find the way.
I've got the query to get the messages of the specific sala, but I can't get the user that created the message.
Mensajes_controller (where I get the messages from the sala)
def index
#mensaje = #sala.mensajes.desc('_id').limit(20)
render json: #mensaje
end
set_sala (to get the room from which I want the messages)
def set_sala
if params[:sala_id]
#sala = Sala.find(params[:sala_id])
end
end
mensaje model
class Mensaje
include Mongoid::Document
include Mongoid::Timestamps::Created
field :cuerpo, type: String
validates :cuerpo, presence: true
belongs_to :user, foreign_key: :user_id
belongs_to :sala, foreign_key: :sala_id
end
user model
class User
include Mongoid::Document
include ActiveModel::SecurePassword
has_secure_password
field :password_digest, type: String
field :email, type: String
field :nombre, type: String
has_many :salas
has_many :mensajes
validates :nombre, presence: true
validates :email, presence: true
validates :password_digest, presence: true
end
Updating - Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.5.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.12'
gem 'bcrypt', '~> 3.1.7'
gem 'mongoid-bcrypt-ruby'
gem 'devise'
gem 'kaminari-mongoid'
gem 'mongo'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem 'mongoid', '~> 7.0.5'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'
gem 'jwt_sessions', '~> 2.3'
gem 'mongoid-rspec', github: 'mongoid/mongoid-rspec', ref: '68c95b133be1a1482fe882e39afd33262147d1f4'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'pry-rails'
gem 'rspec-rails'
gem 'factory_bot_rails'
gem 'shoulda-matchers'
end
group :development do
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Feel free to ask anything you may need. Thanks!
What about this?
#mensaje.user
and install kaminari-mongoid and maybe mongo gem.
Related
I'm studying Ruby on Rails at Coursera's courses. Have a problem implementing task on my current step within current rspec test. It happened after I implemented foreign_key: "racer.racer_id"
These are my classes below and error.
My Racer model class:
class Racer
include Mongoid::Document
embeds_one :info, class_name: "RacerInfo", autobuild: true
has_many :races, class_name: "Entrant", foreign_key: "racer.racer_id", dependent: :nullify, order: :"race.date".desc
before_create do |racer|
racer.info.id = racer.id
end
end
Entrant class:
class Entrant
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: "results"
field :bib, type: Integer
field :secs, type: Float
field :o, as: :overall, type: Placing
field :gender, type: Placing
field :group, type: Placing
embeds_many :results, class_name: "LegResult", after_add: :update_total
embeds_one :race, class_name: "RaceRef"
embeds_one :racer, class_name: "RacerInfo"
default_scope ->{ order(:"event.o".asc) }
def update_total(result)
self[:secs] = results.map {|result| result[:secs]}.inject(:+)
end
def the_race
self.race.race
end
end
RaceRef class:
class RaceRef
include Mongoid::Document
field :n, as: :name, type: String
field :date, type: Date
embedded_in :entrant, class_name: "Entrant"
belongs_to :race, foreign_key: "_id"
end
Error:
Failures:
1) Module #3 Summative: Implement Racers / Results Cross-Collection rq02 Racer has a 1:M linked relationship with Entrant with foreign key in Entrant.RacerInfo
Failure/Error: expect(Racer).to have_many(:races).with_dependent(:nullify).ordered_by(:"race.date".desc)
NameError:
uninitialized constant Mongoid::Contextual::Queryable::Key
# ./spec/racer_results_spec.rb:78:in `block (3 levels) in <top (required)>'
# ./spec/racer_results_spec.rb:17:in `block (2 levels) in <top (required)>'
Gemfile:
source 'https://rubygems.org'
gem 'rails', '~> 4.2.11'
gem 'sqlite3', '~> 1.3.13'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
gem 'spring', '~> 2.0.2'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'mongoid'#, '~> 5.0.0'
group :test do
gem 'rspec-rails', '~> 3.0'
gem 'mongoid-rspec'#, '3.0.0'
gem 'capybara', '~> 3.15.1'
end
gem 'rails-ujs'
gem 'bson', '~> 4.5.0'
Wow! After some manipulating with gem versions I've unstall.
Here is set of gems which have allowed to pass current rspec and make me happy.
source 'https://rubygems.org'
gem 'rails', '4.2.11.1'
gem 'sqlite3', '1.3.13', group: :development
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
end
group :test do
gem 'rspec-rails', '3.3.0'
gem 'mongoid-rspec', '3.0.0'
gem 'capybara', '3.15.1'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'mongoid', '~> 5.4.1'
gem 'bson', '~> 4.5.0'
I should use specific versions of gems 'mongoid', '5.4.1','rspec-rails', '3.3.0' and 'mongoid-rspec', '3.0.0'. After that uninstall other versions to not to use they implicitly in dependencies.
First, I want to say that the models are very difficult to make sense of. Maybe it's because the course wants to go through the various options that Mongoid supports, but there doesn't seem to be a logical structure that underlies the code. In particular the overloading of various race-related nouns and results:
class Entrant
store_in collection: "results"
embeds_many :results, class_name: "LegResult", after_add: :update_total
end
The example given is pretty much spaghetti code.
On to your question, the exception originates in the test file so you'll need to look at what it does (i.e. provide the source to it in your question).
If you are indeed using Mongoid 5 as the gemfile comment suggests, this is another major issue. If you are learning about Mongoid you should be using the current version which is 7. Mongoid 5 is no longer supported. This would require using a newer version of Rails as well (Rails 4 is also not something you should be learning today).
I looked at every possible solution regarding this error but nothing solved it.
Every time I try to upload an image, I receive this error:
Unable to autoload constant ActiveStorage::Blob::Analyzable, expected /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-5.2.2/app/models/active_storage/blob/analyzable.rb to define it.
Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.5.1'
gem 'rails', '~> 5.2.0'
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
# Causing crashes. Removing for now
# gem 'bootsnap', '>= 1.1.0', require: false
# Well maintained fork with several patches and compatability for Rails 5.x
# If we need to we can fork this and take ownership of it. Much better than building from scratch.
# gem 'casino', git: "https://github.com/identification-io/CASino.git", branch: "master"
gem 'casino', git: "https://github.com/webappsllc/CASino.git", branch: "master"
# gem 'casino', path: '/Users/justin/dev/oss/CASino'
gem 'grape', '~> 1.1.0' # Pinned
gem 'wisper', '~> 2.0'
gem 'rack-cors', require: 'rack/cors'
# Form Objects
gem "reform", ">= 2.2.0"
gem "reform-rails"
gem "dry-validation"
# Free optimization
gem 'fast_blank'
# Hashids to obscure legacy_ids
gem 'hashids'
# Send Emails via Amazon SES
gem 'aws-sdk-rails'
# Upload Files via Amason S3
gem "aws-sdk-s3", require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'guard-rspec', require: false
gem 'dotenv-rails', require: 'dotenv/rails-now'
gem 'spring-commands-rspec'
gem 'parallel_tests', group: [:development, :test]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem 'grape_on_rails_routes'
gem "better_errors"
gem "binding_of_caller"
gem "letter_opener"
gem 'letter_opener_web', '~> 1.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15', '< 4.0'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
gem 'factory_bot'
gem 'rspec'
gem 'rspec-rails'
gem 'database_cleaner'
gem 'faker'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
# gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
In config/application.rb I have require 'active_storage/engine' uncommented.
In config/environments/development.rb I have config.active_storage.service = :local set up.
I ran rails active_storage:install and rails db:migrate.
The name of the model is user_test
class UserTest < ApplicationRecord
has_one_attached :image
end
I have this in app/controllers/user_tests_controller.rb
def user_test_params
params.require(:user_test).permit(:title, :caption, :image)
end
**config/storage.yml*
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
I am really clueless as to why it isn't working.
Do you have config.active_storage.service = :amazon set in your development.rb by any chance?
I was getting the above error and it ended up being because I had the above line but the AWS env vars weren't set.
Make sure you check that all of the environment variables present:
AWS access key
AWS secret key
Bucket Name
checking spelling of the environment variables to make sure they match your storage.yml configuration file
Haven't used Rails in a while and just cloned a project, trying to work with the database but I'm getting this uninitialized constant error and I can't seem to figure out why. I bundle installed, created the database, migrated and seeded some files but I can't seem to find the root of the issue. It's not a small project and it seemed to be working fine back when I used it... Any help would be appreciated it...
Here's my gemfile:
source 'https://rubygems.org'
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
gem 'httparty'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt'
gem 'semantic-ui-sass', git: 'https://github.com/doabit/semantic-ui-sass.git'
# gem 'capistrano-rails', group: :development
gem 'pg_search'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'faker'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
gem 'rails_12factor', group: :production
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
And here's the User model:
class User < ApplicationRecord
validates :first_name, :last_name, :presence => true
validates :username, :email, :presence => true, :uniqueness => true
has_many :messages
has_many :posts, :foreign_key => :creator_id
has_many :apprenticeships, :foreign_key => :requestor_id
has_many :skills, through: :posts
has_secure_password
def full_name
"#{self.first_name} #{self.last_name}"
end
end
I have also tried checking if tables were created with ActiveRecord::Base.connection.tables but I'm still getting NameError: uninitialized constant ActiveRecord
Use rails console not irb or pry when working within a Ruby on Rails project. Rails has a complicated bootstrap process, and many of its classes are lazily loaded. Generic interactive consoles like irb or pry do not perform the necessary bootstrap to load a rails app, but rails console will.
Im trying to get Trailblazer-Rails to work in my rails project.
But there seem to be some weird things going on with the reform gem.
I cant start rails with "rails s".
It responds with the error:
"/home/dragonslayer/.rvm/gems/ruby-2.3.1/gems/reform-2.2.3/lib/reform/form/populator.rb:12:in `initialize': uninitialized constant Uber::Options (NameError)
"
but when i remove my contract, it works.
When i remove the conctract it sometimes seem to not be able to find my Operation.
My operation looks like this:
class GuildApplication::Create < Trailblazer::Operation
step Model( GuildApplication, :new)
step Contract::Build( constant: GuildApplication::Contract::Create)
step Contract::Validate()
step :set_status_to_pending
step Contract::Persist()
def set_status_to_pending(options)
options["model"].status = :pending
end
end
My contract:
module GuildApplication::Contract
class Create < Reform::Form
property :first_name
property :last_name
property :email
property :username
property :server
property :spec
property :armory
property :klass
property :played
property :klass_played
property :bio
property :raid_experience
property :reason
property :old_guild
property :progress_raid
property :attendance
property :other
property :screenshot, virtual: true
extend Paperdragon::Model::Writer
processable_writer :image
property :image_meta_data
validates :first_name, :last_name, :email, :username, :server, presence: true
validates :screenshot, file_size: { less_than: 2.megabytes}, file_content_type: { allow: ['image/jpeg', 'image/png'] }
validates_uniqueness_of :email
validates_uniqueness_of :username
end
end
My Controller:
class GuildApplicationsController < ApplicationController
def new
render html: cell(GuildApplication::Cell::Register, nil, layout: Familylegion::Cell::LandingPage)
end
def create
run GuildApplication::Create
end
end
My gemfile:
source 'https://rubygems.org'
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
gem 'rails', '~> 5.0.1'
gem 'mysql2', '>= 0.3.18', '< 0.5'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
#gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'rbattlenet'
gem 'slim'
gem "reform"
gem "reform-rails"
gem "trailblazer"
gem "trailblazer-rails"
gem "cells"
gem "cells-rails"
gem "trailblazer-cells"
gem 'cells-slim'
gem 'dry-validation'
gem 'semantic-ui-sass', github: 'doabit/semantic-ui-sass'
gem 'rmagick'
gem 'paperdragon'
gem 'file_validators'
gem 'capistrano-rails', group: :development
group :development, :test do
gem 'byebug', platform: :mri
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.0.5'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
This issue is fixed in reform 2.2.4, see https://github.com/trailblazer/reform/issues/422 .
I followed the docs at https://github.com/thoughtbot/paperclip exactly to install implement paperclip in my app for image uploading. I am currently using gem 'paperclip', '~> 5.0.0.beta1'. After I did the migration, the four columns were added onto my schema properly:
t.string "picture_file_name"
t.string "picture_content_type"
t.integer "picture_file_size"
t.datetime "picture_updated_at"
My paperclip should therefore be installed correctly. However, when I proceeded to add the following two lines onto my model class:
has_attached_file :picture, styles: { medium: "300*300>", thumb: "100*100" }, default_url: "/images/start_project3.jpg"
validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/
Everything broke. I try to create, search, or anything related to the model class in rails console, it yells at me with the following error:
NoMethodError: undefined method `has_attached_file' for #<Class:0x0055bd71ec0228>
I have tried multiple versions of paperclip, from the earlier version 4.3.0 to the latest version of paperclip, but the problem persists. I also restarted my server in between changes and migrations, but that did not fix the problem. This is the migration that I performed:
class AddAttachmentPictureToProjects < ActiveRecord::Migration
def self.up
change_table :projects do |t|
t.attachment :picture
end
end
def self.down
remove_attachment :projects, :picture
end
end
I am totally lost right now as to what to do.
This is my gem file:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.15'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
gem 'pry-rails'
gem 'annotate'
# Use Unicorn as the app server
# gem 'unicorn'
gem 'faker'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem 'pg_search'
gem 'paperclip', '~> 5.0.0.beta1'
# gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"
# gem "paperclip", "~> 4.3"
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
gem 'faker'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
group :production do
gem 'newrelic_rpm'
gem 'rails_12factor' # error feedback
end
I am not sure what happened. I ended up doing a db roll back and re-migrated the migration yet again. Then I exited all my terminals running in the background and restarted everything. It is working as of now.