undefined method `val' for #<Arel::Nodes::BindParam:0x007fa13ef32028> - ruby-on-rails

I am new to rails, and cannot figure out that why do I get the error specified above when I try to create a new application after login.
Also, while I was looking at solutions online, I found there was something wrong with the foreign key. therefore, I removed the foreign key and added it again using migration. However, the schema.rb file that is shown below does not show an index, but does show Student_id column.
Questions :
Should creation of has_one and belongs_to association require one to mention it in routes.rb as well . ( I read online it does require, but why ? )
How to decide where to place belongs_to and has_one.
How to find out where the above error is generated from ?
Model Student ( created using devise )
class Student < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :student_application
end
StudentApplication ( Generate using scaffold)
class StudentApplication < ActiveRecord::Base
belongs_to :Student
end
routes.rb
Rails.application.routes.draw do
resources :student_applications
devise_for :students
root to: "student_applications#index"
end
In the controller student_application_controller.rb
def new
##student_application = StudentApplication.new
#student_application = current_student.build_student_application()
end
def create
##student_application = StudentApplication.new(student_application_params)
##new_student = Student.find(params[:id])
#student_application = current_student.create_student_application(student_application_params)
respond_to do |format|
if #student_application.save
format.html { redirect_to #student_application, notice: 'Student application was successfully created.' }
format.json { render :show, status: :created, location: #student_application }
else
format.html { render :new }
format.json { render json: #student_application.errors, status: :unprocessable_entity }
end
end
end
private
def student_application_params
params.require(:student_application).permit(:Student_id, :name, :phone, :email_id, :gpa)
end
schema.rb
create_table "student_applications", force: :cascade do |t|
t.string "name"
t.string "phone"
t.string "email_id"
t.decimal "gpa"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "Student_id"
end
create_table "students", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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.datetime "created_at"
t.datetime "updated_at"
end
add_index "students", ["email"], name: "index_students_on_email", unique: true
add_index "students", ["reset_password_token"], name: "index_students_on_reset_password_token", unique: true
end

Related

Actiontext image upload fails in Rails 7

I am attempting to use the trix/actiontext feature of rails 7 to upload images to be included in my blog. I am planning to store them in AWS-S3 bucket, but the problem also happens when trying to store on local disk. Trix works normally when just doing text content with no errors. When I click the "paperclip" icon to attach a file, I get prompted to select a file, and it appears that I am able to, however, there are errors in the console and when I click submit, the file does not save.
This is the error in the console as soon as I choose an image to attach:
POST http://localhost:3000/rails/active_storage/direct_uploads 422
(Unprocessable Entity) actiontext.js:543
Uncaught Error: Direct upload failed: Error creating Blob for
"Screenshot from 2022-10-13 12-38-57.png". Status: 422
at AttachmentUpload.directUploadDidComplete (actiontext.js:849:13)
at BlobRecord2.callback (actiontext.js:618:13)
at BlobRecord2.requestDidError (actiontext.js:560:12)
at BlobRecord2.requestDidLoad (actiontext.js:556:14)
at XMLHttpRequest. (actiontext.js:527:56)
Here is the error from the rails server:
Started POST "/rails/active_storage/direct_uploads" for ::1 at
2022-11-03 14:20:10 -0500 14:20:10 web.1 | Processing by
ActiveStorage::DirectUploadsController#create as JSON 14:20:10 web.1
| Parameters: {"blob"=>{"filename"=>"Screenshot from 2022-10-26
15-49-39.png", "content_type"=>"image/png", "byte_size"=>336871,
"checksum"=>"TZneH7Z7DdCSftEvona6zg=="},
"direct_upload"=>{"blob"=>{"filename"=>"Screenshot from 2022-10-26
15-49-39.png", "content_type"=>"image/png", "byte_size"=>336871,
"checksum"=>"TZneH7Z7DdCSftEvona6zg=="}}} 14:20:10 web.1
Completed 422 Unprocessable Entity in 33ms (ActiveRecord: 8.4ms |
Allocations: 14851)
ActiveRecord::RecordInvalid (Validation failed: Service name can't be
blank): 14:20:10
There is of course a much longer stack trace, but that appears to be the important part. I'm happy to provide the rest if anyone wants it.
When I click submit on the form, I get my normal toast message saying blog is successfully updated, but the image file is not added to the post. I've been searching for the answer to this problem for 3 days and I'm starting to go around in circles. I know that service_name is a column in the actives_storage_blobs database table, but I don't know where it pulls service name from or how to get it there. I'm thinking it's from the service in storage.yml, and it is present there.
storage.yml:
local:
service: Disk
root: <%= Rails.root.join("storage") %>
I'm running out of things to try and search for this problem. I have disabled turbo for the blogs page as I had found a github discussion relating to that, but it hasn't helped. I have read through the guides for active storage and action text multiple times and have not found anything that helped. I would greatly appreciate any suggestions. Thank you.
In case it helps:
Here is the relevant part of the form at app/views/blogs/_form.html.erb:
<div class="form-group">
<%= form.rich_text_area :body, class: 'form-control', rows: 15, placeholder: 'Content' %>
</div>
app/controllers/blogs_controller.rb:
class BlogsController < CommentsController
before_action :set_blog, only: %i[ show edit update destroy toggle_status ]
before_action :set_sidebar_topics, except: [:update, :create, :destroy, :toggle_status]
layout "blog"
access all: [:show, :index], user: { except: [:destroy, :new, :create, :update, :edit, :toggle_status] }, admin: :all, testing: { except: [:destroy, :create, :update]}
def index
if logged_in?(:admin) || logged_in?(:testing)
#blogs = Blog.recent.with_rich_text_body_and_embeds.page(params[:page]).per(5)
else
#blogs = Blog.published.recent.with_rich_text_body_and_embeds.page(params[:page]).per(5)
end
#page_title = "My Portfolio Blog"
end
def show
if logged_in?(:admin) || logged_in?(:testing) || #blog.published?
#blog = Blog.includes(:comments).friendly.find(params[:id])
#comment = Comment.new
#page_title = #blog.title
#seo_keywords = #blog.body
else redirect_to blogs_path, notice: 'You are not authorized to access this page.'
end
end
def new
#blog = Blog.new
end
def edit
end
def create
#blog = Blog.new(blog_params)
respond_to do |format|
if #blog.save
format.html { redirect_to blog_url(#blog), success: "Blog was successfully created." }
else
flash[:danger] = "Blog must have title, body and topic."
format.html { render :new, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #blog.update(blog_params)
format.html { redirect_to blog_url(#blog), success: "Blog was successfully updated." }
else
format.html { render :edit, status: :unprocessable_entity }
end
end
end
def destroy
#blog.destroy
respond_to do |format|
format.html { redirect_to blogs_url, status: :see_other }
end
end
def toggle_status
if #blog.draft? && logged_in?(:admin)
#blog.published!
elsif #blog.published? && logged_in?(:admin)
#blog.draft!
end
redirect_to blogs_url, success: 'Post status has been updated.'
end
private
def set_blog
#blog = Blog.friendly.find(params[:id])
end
def blog_params
params.require(:blog).permit(:title, :body, :topic_id, :status, images: [])
end
def set_sidebar_topics
#side_bar_topics = Topic.with_blogs
end
end
app/models/blog.rb:
class Blog < ApplicationRecord
enum status: { draft: 0, published: 1 }
extend FriendlyId
friendly_id :title, use: :slugged
validates_presence_of :title, :body, :topic_id
has_rich_text :body
has_many_attached :images, dependent: :destroy
has_many :comments, as: :commentable, dependent: :destroy, counter_cache: :commentable_count
belongs_to :topic, optional: true
def self.special_blogs
all
end
def self.featured_blogs
limit(2)
end
def self.recent
order("updated_at DESC")
end
end
ActiveRecord::Schema[7.0].define(version: 2022_10_14_225319) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "action_text_rich_texts", force: :cascade do |t|
t.string "name", null: false
t.text "body"
t.string "record_type", null: false
t.bigint "record_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["record_type", "record_id", "name"], name: "index_action_text_rich_texts_uniqueness", unique: true
end
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.bigint "record_id", null: false
t.bigint "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.string "service_name", null: false
t.bigint "byte_size", null: false
t.string "checksum"
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "active_storage_variant_records", force: :cascade do |t|
t.bigint "blob_id", null: false
t.string "variation_digest", null: false
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
end
create_table "blogs", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.integer "status", default: 0
t.bigint "topic_id"
t.integer "commentable_count"
t.text "body"
t.index ["slug"], name: "index_blogs_on_slug", unique: true
t.index ["topic_id"], name: "index_blogs_on_topic_id"
end
create_table "comments", force: :cascade do |t|
t.bigint "user_id", null: false
t.string "commentable_type", null: false
t.bigint "commentable_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "body"
t.index ["commentable_type", "commentable_id"], name: "index_comments_on_commentable"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "friendly_id_slugs", force: :cascade do |t|
t.string "slug", null: false
t.integer "sluggable_id", null: false
t.string "sluggable_type", limit: 50
t.string "scope"
t.datetime "created_at"
t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
end
create_table "portfolios", force: :cascade do |t|
t.string "title"
t.string "subtitle"
t.text "body"
t.text "main_image"
t.text "thumb_image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "position"
end
create_table "skills", force: :cascade do |t|
t.string "title"
t.integer "percent_utilized"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "badge"
end
create_table "technologies", force: :cascade do |t|
t.string "name"
t.bigint "portfolio_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["portfolio_id"], name: "index_technologies_on_portfolio_id"
end
create_table "topics", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "name"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "roles"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
add_foreign_key "blogs", "topics"
add_foreign_key "comments", "users"
add_foreign_key "technologies", "portfolios"
end
I am going to stop this question. It appears that rails needed updating. I did rails app:update and there were updates related to actiontext and activestorage and the DB schema was updated for those 3 relevant tables. I have done an upload through action text and it has worked. It's not displaying properly but there is data in my storage folder. I am going to go through everything as it is now to see if I can get the image to display properly and will ask a new question if needed. Thank you very much for helping.
Edit to add: Updating rails did fix the uploads completely. The update changed the image processor from mini-magick to vips. Adding this line to application.rb switched it back and then everything worked properly.
config.active_storage.variant_processor = :mini_magick

Rails many-to-many through relationship returning empty array

I'm a beginner in rails and am making a card app. I have a user, card, and user_card models with a many to many, through relationship set up between the cards and users. My problem is that when I return the card table and try to include: the users I get an empty array. I've tried resetting the database but still nothing.
ActiveRecord::Schema.define(version: 2022_06_15_200100) do
create_table "cards", force: :cascade do |t|
t.string "name"
t.string "image"
t.string "text"
t.integer "level"
t.string "types"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "quantity", default: 0
end
create_table "user_cards", force: :cascade do |t|
t.integer "user_id"
t.integer "card_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["card_id"], name: "index_user_cards_on_card_id"
t.index ["user_id"], name: "index_user_cards_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
class User < ApplicationRecord
has_secure_password
has_many :user_cards
has_many :cards, through: :user_cards
end
class Card < ApplicationRecord
has_many :user_cards
has_many :users, through: :user_cards
end
class UserCard < ApplicationRecord
belongs_to :user
belongs_to :card
end
controller
class CardsController < ApplicationController
wrap_parameters false
def create
card = Card.create(card_params)
if card.valid?
render json: card, status: :created, include: :users
else
render json:{errors: card.errors}
end
def index
card = Card.all
render json: card, include: :users
end
In order for the User.first.cards to work, you need to ensure the application is inserting data in the user_cards table.
You may check if there are any records in there by doing UserCard.all in your rails console.
Coming to the controller, after creating a card record, you have to assign it to a user record in order for the relationship to be established.
def create
card = Card.create(card_params)
if card.valid?
card.users << current_user # Or card.users << (any user object like) User.first
render json: card, status: :created, include: :users
else
render json:{errors: card.errors}
end
end
card.users << user object will create the necessary record in the user_cards table and you'll be able to access them using includes: :user
You may refer the examples given - here in the Rails API guide

Rails not assigning proper ids

I have a program with service_provider and service models. The service_provider uses the has_many attribution and the service model uses belongs_to attribution. service_provider was created using devise. I am unable to assign a service_provider_id to the service in the create method.
The create method in services_controller.rb
def create
#service = Service.new(service_params)
#service.service_provider_id = current_service_provider.id
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render :show, status: :created, location: #service }
else
format.html { render :new }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
The rails console gives service_provider_id: nil for every service.
Here's the schema.rb where service_provider_id was created using the migration "t.belongs_to :service_provider, index: true"
create_table "service_providers", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "service_providers", ["email"], name: "index_service_providers_on_email", unique: true
add_index "service_providers", ["reset_password_token"], name: "index_service_providers_on_reset_password_token", unique: true
create_table "services", force: :cascade do |t|
t.integer "service_provider_id"
t.string "service_name"
t.text "description"
t.integer "price"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "services", ["service_provider_id"], name: "index_services_on_service_provider_id"
Here's the service.rb model
class Service < ActiveRecord::Base
attr_accessor :service_provider_id
belongs_to :service_provider
validates_presence_of :description, :location, :service_name, :price
end
And the 'service_provider.rb`
class ServiceProvider < ActiveRecord::Base
has_many :services
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
I tried restarting the server and resetting the database with no luck.
Just to remove attr_accessor :service_provider_id from service.rb
rake db:migrate then rails s
as #Petr mentioned it overrides (calling it 2nd time for nil).

Unsure if association is working in my rails app

My app has users and users are able to post links to my app. I have an association set up so that a user has many :links and links belong_to a user (see below for models). Now I am trying to get the users email to appear in the show template and I am getting a nil value for Link.user for new links. Can someone maybe shed some light as to why? Is my association incorrect? The user has been logged in when posting links.
User model:
class User < ActiveRecord::Base
has_many :links
acts_as_voter
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Link model:
class Link < ActiveRecord::Base
belongs_to :user
acts_as_votable
attr_accessor :avatar
mount_uploader :avatar, AvatarUploader
end
show.html.erb:
<%= time_ago_in_words(#link.created_at) %> by <%= #link.user.try(:email) %>
Schema:
create_table "links", force: :cascade do |t|
t.string "title"
t.string "url"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Link creation in Links controller;
def new
#link = Link.new
end
def create
#link = Link.new(link_params)
if #link.save
redirect_to root_path
else
render 'new'
end
end
private
def link_params
params.require(:link).permit(:title, :url, :avatar)
end
Make sure the links are actually being assigned to a user when created.
Using the rails console. Try looping through the links and making sure they have user_ids:
in the rails console:
ap Link.all.map(&:user)
If they are indeed owned by a user
<%= #link.user.email %>
should print out the email.
You should be able to do something like this in your controller:
#user.links << params[:new_link]
Make sure that much is working.
You are using devise. Inside your Link controller, you have to authenticate your logged on user.
# app/controllers/links_controller.rb
before_action :authenticate_user!
def create
#link = current_user.links.new(link_params)
if #link.save
redirect_to root_path
else
render 'new' # generally this is a render 'edit'
end
end
I truncated the file here. Please read the devise manual

Ruby on Rails SQLite3::ConstraintException: NOT NULL constraint failed:

I am developing a simple app where a user can add a subject to a cart. Before I add the authentication I was able to add a subject to the cart but as I want a user to be able to has access to just his/her cart I used Devise to create User with authentication. Now, when I click on the button to add a subject to the cart I have the following error:
This is a snapshot of the error I get: 1
SQLite3::ConstraintException: NOT NULL constraint failed: carts.user_id: INSERT INTO "carts" ("created_at", "updated_at") VALUES (?, ?)
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def current_cart
Cart.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
params[:user_id] = cart.id
cart
end
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :cart
end
class Cart < ActiveRecord::Base
belongs_to :user
has_many :line_items, dependent: :destroy
scope :user_carts, ->(user) { where(['user_id= ?', user.id]) }
end
class AddUsersToCarts < ActiveRecord::Migration
def up
add_reference :carts, :user, index: true
Cart.reset_column_information
user = User.first
Cart.all.each do |cart|
cart.user_id = user.id
cart.save!
end
change_column_null :carts, :user_id, false
add_foreign_key :carts, :users
end
def down
remove_foreign_key :carts, :users
remove_reference :carts, :user, index: true
end
end
Edit: I added the schema.rb below:
ActiveRecord::Schema.define(version: 20151210213408) do
create_table "carts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id", null: false
end
add_index "carts", ["user_id"], name: "index_carts_on_user_id"
create_table "line_items", force: :cascade do |t|
t.integer "subject_id"
t.integer "cart_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "subjects", force: :cascade do |t|
t.string "title", null: false
t.string "code", null: false
t.text "description", null: false
t.integer "credits", null: false
t.string "lecturer", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "subjects", ["title"], name: "index_subjects_on_title", unique: true
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
You current_cart method does not make much sense.
You cannot find the user's cart by calling Cart.find(params[:user_id]), because that looks for a cart by an id (not by an user_id).
Cart.create fails, because you do not provide an user_id that is required (your database migrations says that the filed cannot be null).
Furthermore, params[:user_id] = cart.id changes the params hash, but not the new cart.
Change that method to something like this (using find_or_create_by) and use the current_user.id instead of params[:user_id]:
def current_cart
Cart.find_or_create_by(user_id: current_user.id)
end

Resources