I have 2 models: Customer and Sale
class Sale < ApplicationRecord
belongs_to :customer, inverse_of: :sales
accepts_nested_attributes_for :customer
end
class Customer < ApplicationRecord
has_many :sales, inverse_of: :customer
end
In SALE controller i have a form with CUSTOMER'S values
To create new sale i don't have any problem, but when i try update, the error "unknown attribute 'valor_oferta' for Customer" appears
Sale Controller
class SalesController < ApplicationController
before_action :authenticate_user!
def new
#sale = Sale.new
#sale.build_customer
end
def create
#sale = Sale.new(proposta_params)
respond_to do |format|
if #sale.save
format.html { redirect_to dashboard_path, notice: 'Proposta criada com sucesso.' }
else
format.html { render :new }
#sale.errors.each do |erro|
puts erro
end
end
end
end
def edit
#sale = Sale.find(params[:id])
#sale.customer
end
def update
#sale = Sale.find(params[:id])
respond_to do |format|
if #sale.customer.update(proposta_params)
format.html { redirect_to dashboard_path, notice: 'Proposta alterada com sucesso.' }
else
format.html { render :edit }
#sale.errors.each do |erro|
puts erro
end
end
end
end
private
def proposta_params
params.require(:sale).permit(:valor_oferta, :grupo_promocao, :codigo_oferta, :modo_pagamento, :vencimento, :banco, :agencia, :conta, :isento, :valor, :data_envio_qualidade, :data_agendamento_qualidade, :janela_agendamento, :data_instalacao_qualidade,:tv_id, :phone_id, :internet_id, :equipamentos, :cep, :rua, :numero, :complemento, :bairro, :cidade, :uf, :ponto_de_referencia, :obs, customer_attributes: [:name, :cpf_pf, :nascimento_pf, :nome_mae_pf, :nome_mae_pf, :cnpj_pj, :fundacao_pj, :telefone1, :telefone2, :telefone3, :email, :juridica])
end
end
I already tried use only
if #sale.update(proposta_params)
but in this case, another Customer is created and not updated
I use Rails 5
#################EDIT
db/schema.rb
create_table "sales", force: :cascade do |t|
t.integer "lead_id"
t.string "solicitante"
t.integer "protocolo"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "tv_id"
t.integer "phone_id"
t.integer "internet_id"
t.string "solicitante_pf"
t.string "valor_oferta"
t.string "grupo_promocao"
t.string "codigo_oferta"
t.string "vencimento"
t.boolean "isento"
t.string "valor"
t.string "data_envio_qualidade"
t.string "data_agendamento_qualidade"
t.string "janela_agendamento"
t.string "data_instalacao_qualidade"
t.integer "customer_id"
t.string "agencia"
t.string "conta"
t.string "banco"
t.string "modo_pagamento"
t.integer "equipamentos"
t.string "cep"
t.string "rua"
t.string "numero"
t.string "complemento"
t.string "bairro"
t.string "cidade"
t.string "uf"
t.string "ponto_de_referencia"
t.text "obs"
t.integer "user_id"
t.integer "user_qualidade_id"
t.integer "status_sale_id"
t.index ["customer_id"], name: "index_sales_on_customer_id", using: :btree
t.index ["internet_id"], name: "index_sales_on_internet_id", using: :btree
t.index ["lead_id"], name: "index_sales_on_lead_id", using: :btree
t.index ["phone_id"], name: "index_sales_on_phone_id", using: :btree
t.index ["status_sale_id"], name: "index_sales_on_status_sale_id", using: :btree
t.index ["tv_id"], name: "index_sales_on_tv_id", using: :btree
t.index ["user_id"], name: "index_sales_on_user_id", using: :btree
end
Related
I'm building an API for an app where a user can make appointments with a doctor.
Everything is working just fine but it's returning 204 - No content when I try to post a new appointment in Postman.
My schema:
create_table "appointments", force: :cascade do |t|
t.date "date"
t.time "time"
t.bigint "user_id"
t.bigint "doctor_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["doctor_id"], name: "index_appointments_on_doctor_id"
t.index ["user_id"], name: "index_appointments_on_user_id"
end
create_table "doctors", force: :cascade do |t|
t.string "name"
t.string "speciality"
t.integer "years_of_experience"
t.integer "likes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "password_digest"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_foreign_key "appointments", "doctors"
add_foreign_key "appointments", "users"
end
My appointments controller:
class Api::V1::AppointmentsController < ApplicationController
include CurrentUserConcern
def index
#appointments = Appointment.all
render json: #appointments
end
def create
if #current_user
#appointment = #current_user.appointments.build(appointment_params)
if #appointment.save
render json: #appointment
else
render json: { status: 401 }
end
end
end
private
def appointment_params
params.require(:appointment).permit(:time, :date, #current_user.id, :doctor_id)
end
end
First of all there's not need of sending #current_user.id in appointment_params as user_id will be assigned automatically when this line #appointment = #current_user.appointments.build(appointment_params) execute.
Coming to your issue make sure you are sending a POST request and "body" data in the correct JSON format from PostMan. As per your method appointment_params the request body should look like this
{
appointment: {
time: "",
date: "",
doctor_id:
}
}
I am quite new on RoR.
I have two models, one User (generated by Devise) and one Profile.
I want to have one Profile per User.
Here are my User stories:
As a user I have to, create a Profile
As a user I can, edit my Profile
As a user I can, see all the Profiles
Below, you will see my two different models.
class Profile < ApplicationRecord
has_attachment :photo
belongs_to :user, class_name: 'User', foreign_key: :user_id
end
class User < ApplicationRecord
has_one :profile
devise :database_authenticatable, :registerable,
:rememberable, :trackable, :validatable
end
I don't know why, but today, a User can create many Profile and Edit another Profile.
Does anyone could help me to understand why ?
In order to prevent users to edit others profile you can do something like this in your Profile controller update action
if current_user == #profile.user
allow to edit
else
don't allow to edit
Here is my schema.rb
ActiveRecord::Schema.define(version: 20160510084050) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "attachinary_files", force: :cascade do |t|
t.string "attachinariable_type"
t.integer "attachinariable_id"
t.string "scope"
t.string "public_id"
t.string "version"
t.integer "width"
t.integer "height"
t.string "format"
t.string "resource_type"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "attachinary_files", ["attachinariable_type", "attachinariable_id", "scope"], name: "by_scoped_parent", using: :btree
create_table "bookings", force: :cascade do |t|
t.integer "user_id"
t.integer "profile_id"
t.boolean "status"
t.date "teetime"
t.text "message"
end
add_index "bookings", ["profile_id"], name: "index_bookings_on_profile_id", using: :btree
add_index "bookings", ["user_id"], name: "index_bookings_on_user_id", using: :btree
create_table "mailboxer_conversation_opt_outs", force: :cascade do |t|
t.string "unsubscriber_type"
t.integer "unsubscriber_id"
t.integer "conversation_id"
end
add_index "mailboxer_conversation_opt_outs", ["conversation_id"], name: "index_mailboxer_conversation_opt_outs_on_conversation_id", using: :btree
add_index "mailboxer_conversation_opt_outs", ["unsubscriber_id", "unsubscriber_type"], name: "index_mailboxer_conversation_opt_outs_on_unsubscriber_id_type", using: :btree
create_table "mailboxer_conversations", force: :cascade do |t|
t.string "subject", default: ""
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "mailboxer_notifications", force: :cascade do |t|
t.string "type"
t.text "body"
t.string "subject", default: ""
t.string "sender_type"
t.integer "sender_id"
t.integer "conversation_id"
t.boolean "draft", default: false
t.string "notification_code"
t.string "notified_object_type"
t.integer "notified_object_id"
t.string "attachment"
t.datetime "updated_at", null: false
t.datetime "created_at", null: false
t.boolean "global", default: false
t.datetime "expires"
end
add_index "mailboxer_notifications", ["conversation_id"], name: "index_mailboxer_notifications_on_conversation_id", using: :btree
add_index "mailboxer_notifications", ["notified_object_id", "notified_object_type"], name: "index_mailboxer_notifications_on_notified_object_id_and_type", using: :btree
add_index "mailboxer_notifications", ["sender_id", "sender_type"], name: "index_mailboxer_notifications_on_sender_id_and_sender_type", using: :btree
add_index "mailboxer_notifications", ["type"], name: "index_mailboxer_notifications_on_type", using: :btree
create_table "mailboxer_receipts", force: :cascade do |t|
t.string "receiver_type"
t.integer "receiver_id"
t.integer "notification_id", null: false
t.boolean "is_read", default: false
t.boolean "trashed", default: false
t.boolean "deleted", default: false
t.string "mailbox_type", limit: 25
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "is_delivered", default: false
t.string "delivery_method"
t.string "message_id"
end
add_index "mailboxer_receipts", ["notification_id"], name: "index_mailboxer_receipts_on_notification_id", using: :btree
add_index "mailboxer_receipts", ["receiver_id", "receiver_type"], name: "index_mailboxer_receipts_on_receiver_id_and_receiver_type", using: :btree
create_table "profiles", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "handicap"
t.string "postbox"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "tagline"
t.string "skills"
t.string "town"
t.integer "user_id"
t.float "latitude"
t.float "longitude"
t.string "street"
end
add_index "profiles", ["user_id"], name: "index_profiles_on_user_id", using: :btree
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.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "prenom"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_foreign_key "bookings", "profiles"
add_foreign_key "bookings", "users"
add_foreign_key "mailboxer_conversation_opt_outs", "mailboxer_conversations", column: "conversation_id", name: "mb_opt_outs_on_conversations_id"
add_foreign_key "mailboxer_notifications", "mailboxer_conversations", column: "conversation_id", name: "notifications_on_conversation_id"
add_foreign_key "mailboxer_receipts", "mailboxer_notifications", column: "notification_id", name: "receipts_on_notification_id"
add_foreign_key "profiles", "users"
end
And here is the profile controller
class ProfilesController < ApplicationController
skip_before_action :authenticate_user!, only: [ :index ]
before_action :find_profiles, only: [:show, :edit, :update, :destroy]
def index
# if params[:id]
# #profiles = Profile.where(handicap: params[:handicap])
# else
#profiles = Profile.all
#hash = Gmaps4rails.build_markers(#profiles) do |profile, marker|
marker.lat profile.latitude
marker.lng profile.longitude
marker.infowindow render_to_string(partial: "/profiles/map_box", locals: { profile: profile })
end
end
end
def show
#profile = Profile.find(params[:id])
end
def new
#profile = Profile.new
end
def create
owner = current_user
#profile = Profile.new(profile_params)
#profile.owner = owner
if #profile.save
redirect_to profiles_path
else
render :new
end
end
def edit
end
def update
if #profile.update(profile_params)
redirect_to profiles_path
else
render :edit
end
end
def destroy
end
private
def profile_params
params.require(:profile).permit(:last_name,:first_name, :address, :search, :handicap, :street, :postbox, :tagline, :skills, :town, :photo)
end
def find_profiles
#profile = Profile.find(params[:id])
end
end
My problem is similar to:
My cloning method is stealing the children from the original model
But I can't seem to get the solution for this to work with mine. I'm trying to create an order exchange form which involves populating the form with the old record details. So when I save the form it creates a new Order record but the children seem to get deleted from the old Order record and siphoned into the new one.
Here's the code:
def new
#old_order = Order.includes(:line_items).find(params[:id])
#order = Order.new #old_order.attributes
#order.line_items = []
#old_order.line_items.each do |old|
new = old.dup # the line_item id is set before creation.
new.order_id = #order.id
new.save!
#order.line_items << new
#old_order.line_items << old # this was to see if the old line_items would reappend to the old order. Didn't help...
end
end
def create
#order = Order.new(exchange_order_params)
if #order.save
#order.update_attributes!(stage: 2, ordered_at: Date.today)
redirect_to admin_returns_url, notice: "Order moved to 'accepted' for processing"
else
flash.now[:alert] = "Please try again"
render :action => "new"
end
end
private
def exchange_order_params
params.require(:order).permit(:id, :user_id,
line_items_attributes: [:id, :order_id, :cart_id, :quantity, :_destroy,
product_attributes: [:id, :sku, :euro_price, :sterling_price, :product_group_id, :product_size_id, :product_waistband_id]])
end
Schema.rb
create_table "orders", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "returned", default: false
t.date "date_sent"
t.date "ordered_at"
t.integer "user_id"
t.boolean "return_requested", default: false
t.integer "stage", default: 0
t.decimal "order_total", default: 0.0
t.string "transaction_secret"
t.string "token"
t.string "uuid"
t.string "currency"
t.float "discounted_by", default: 0.0
end
add_index "line_items", ["cart_id"], name: "index_line_items_on_cart_id", using: :btree
add_index "line_items", ["order_id"], name: "index_line_items_on_order_id", using: :btree
add_index "line_items", ["product_id"], name: "index_line_items_on_product_id", using: :btree
create_table "line_items", force: :cascade do |t|
t.integer "quantity"
t.integer "order_id"
t.integer "cart_id"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "unit_price"
t.string "currency"
end
create_table "product_groups", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "product_sizes", force: :cascade do |t|
t.string "specification"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "product_waistbands", force: :cascade do |t|
t.string "specification"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.integer "sku"
t.integer "product_group_id"
t.integer "product_size_id"
t.integer "product_waistband_id"
t.decimal "euro_price"
t.decimal "sterling_price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "stock_level", default: 0
end
add_index "products", ["product_group_id"], name: "index_products_on_product_group_id", using: :btree
add_index "products", ["product_size_id"], name: "index_products_on_product_size_id", using: :btree
add_index "products", ["product_waistband_id"], name: "index_products_on_product_waistband_id", using: :btree
Also in the Order model I am randomising the id before_create so that when the user submits the form, it creates a dupe copy with a different Order id. This is the same for LineItems.
Order.rb (same in LineItem.rb)
before_create :randomize_id
private
def randomize_id
begin
self.id = SecureRandom.random_number(1_000_000)
end while Order.where(id: self.id).exists?
end
My approach would be to override the ActiveRecord::Base#dup method in the Order model so that it's recursive, meaning that it also duplicates the LineItem collection:
class Order < ActiveRecord::Base
def dup
duped_order = super
duped_order.line_items = line_items.map(&:dup)
duped_order
end
end
doing it this way makes it easily testable. Now the controller becomes:
class OrderController < ApplicationController
def new
#order = Order.find(params[:id]).dup
end
def create
# not sure how your form populates the params hash
# here you need to new-up and then save the order and the line items
# with the attributes from the form
end
end
Do write tests to confirm that this is doing what you intend. This is the perfect example of where the old "fat model skinny controller" paradigm should be applied.
I am having trouble trying to achieve the following, mostly in the controller part:
I have a User model and a Firm model.
A User can create a Firm, this will mean that this user will be the firm owner. Additionally, this user can add other users to join the firm.
So far, my Models are as follows:
class Firm< ActiveRecord::Base
has_many :users, dependent: :destroy
end
class User < ActiveRecord::Base
...
belongs_to :bufete
end
Here is my create action in my firms controller:
def create
#bufete = Bufete.create(bufete_params)
#user = current_user
#bufete.users.create(#user) # Mark that this user belongs to a bufete
#user.owner = true # Mark this user as the owner of the Bufete
respond_to do |format|
if #bufete.save && #user.save
format.html { redirect_to #bufete, :flash => { :success => 'Tu bufete ha sido creado exitosamente.' } }
format.json { render :show, status: :created, location: #bufete }
else
format.html { render 'new', :flash => { :danger => 'Hubo un error al tratar de crear tu bufete.
Porfavor asegurese de que el correo electronico es una direccion valida' } }
format.json { render json: #bufete.errors, status: :unprocessable_entity }
end
end
end
Schema.rb file:
ActiveRecord::Schema.define(version: 20150730061404) do
create_table "bufetes", force: :cascade do |t|
t.string "name"
t.string "address"
t.string "telephone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "description"
t.string "code"
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
t.boolean "admin", default: false
t.boolean "premium", default: false
t.integer "bufete_id"
t.string "name"
t.string "last_name"
t.boolean "owner", default: 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
I believe my associations are correct, but I could be mistaken. My main problem is in the controller. When a user creates a firm, how do I assign this user to be the owner of this Firm? At the same time how do I add this user to the Firm.users collection?
Also, how would I go for adding future users to a specific firm's users collection?
Important: A user can only create ONE Firm. At the same time, a user can only belong to ONE firm as well. If a user creates a firm, it will belong to THAT firm.
I assume Bufete is equal to Firm model, in the code below I'll use Bufete instead of Firm. You can check whether the user can create a new Bufete before creating the Bufete record.
def create
#user = current_user
if #user.can_create_bufete?
#bufete = Bufete.create(bufete_params)
# assign user to #bufete instead of #bufete.users.create()
#user.bufete = #bufete
#user.owner = true
# add your response_to block for #user.saved
else
# add your response_to block of not creating new Bufete
end
end
Then you'll check whether the user can create a Bufete object or not in your User model.
def can_create_bufete?
!owner && !bufete.present? # or any condition that meets your requirement
end
I am not sure why my query works on localhost but is failing on the server.
This happens when i try to create a quiz which routes to QuizzesController#new
# GET /quizzes/new
def new
#quiz = current_user.quizzes.new
end
This is the query:
SELECT COUNT(*) FROM "questions" INNER JOIN "question_categories" ON "question_categories"."question_id" = "questions"."id" WHERE "questions"."deleted_at" IS NULL AND (`question_categories`.`category_id` IN (87,1))
(1.0ms) ROLLBACK
Completed 500 Internal Server Error in 58ms (ActiveRecord: 13.4ms)
And i got an error as such.
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "." LINE 1: ...s"."deleted_at" IS NULL AND (`question_categories`.`category...
quiz.rb
before creating i would run build_parts which should randomly grab questions and place them into quizzes.
class Quiz < ActiveRecord::Base
belongs_to :user
belongs_to :subject
has_many :quiz_categories
has_many :categories, through: :quiz_categories
has_many :quiz_parts
accepts_nested_attributes_for :categories
accepts_nested_attributes_for :quiz_parts
validates :user, :subject, :number_of_questions, presence: true
validates :number_of_questions, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
before_create :build_parts
before_save :set_completed_at, if: -> { completeness == 100.00 }
def completeness
answerable_quiz_parts = 0
quiz_parts.each do |q_part|
answerable_quiz_parts += 1 if q_part.answerable.answers.present?
end
quiz_parts.joins(:choice).count.to_f * 100 / answerable_quiz_parts
end
def score
quiz_parts.joins(:choice).where('choices.correct = ?', true).count { |qp| qp.choice.correct? }
end
private
# select random questions
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('`question_categories`.`category_id` IN (?)', category_ids)
#self.number_of_questions = [number_of_questions, question_pool.size].min
puts question_pool.size
if number_of_questions > question_pool.size
errors.add(:number_of_questions, 'is too high. Please select a lower question count or increase category selections')
return false
end
number_of_questions.times do |i|
question_pool.inspect
self.quiz_parts << question_pool[i].quiz_parts.new
question_pool[i].question_parts.each do |question_part|
self.quiz_parts << question_part.quiz_parts.new
end
end
end
def set_completed_at
self.completed_at = Time.zone.now
end
end
quizzes_controller.rb
class QuizzesController < ApplicationController
before_action :authenticate_user!
before_action :set_quiz, only: [:show, :edit, :update, :destroy]
# GET /quizzes
# GET /quizzes.json
def index
#quizzes = current_user.quizzes.order(created_at: :desc)
end
# GET /quizzes/1
# GET /quizzes/1.json
def show
end
# GET /quizzes/new
def new
#quiz = current_user.quizzes.new
end
# GET /quizzes/1/edit
def edit
end
# POST /quizzes
# POST /quizzes.json
def create
#quiz = current_user.quizzes.new(quiz_create_params)
respond_to do |format|
if #quiz.save
format.html { redirect_to edit_quiz_path(#quiz), notice: 'Quiz was successfully created.' }
format.json { render :show, status: :created, location: #quiz }
else
format.html { render :new }
format.json { render json: #quiz.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /quizzes/1
# PATCH/PUT /quizzes/1.json
def update
respond_to do |format|
if #quiz.update(quiz_update_params)
format.html { redirect_to #quiz, notice: 'Quiz was successfully updated.' }
format.json { render :show, status: :ok, location: #quiz }
else
format.html { render :edit }
format.json { render json: #quiz.errors, status: :unprocessable_entity }
end
end
end
# DELETE /quizzes/1
# DELETE /quizzes/1.json
def destroy
#quiz.destroy
respond_to do |format|
format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_quiz
#quiz = current_user.quizzes.find(params[:id])
end
# For quiz setup
def quiz_create_params
params.require(:quiz).permit(:subject_id, :number_of_questions, category_ids: [])
end
# For quiz answering
def quiz_update_params
params.require(:quiz).permit(quiz_parts_attributes: [:id, choice_attributes: [:id, :content, :answer_id, :_destroy]])
end
end
schema.rb:
ActiveRecord::Schema.define(version: 20150726180000) do
create_table "admins", force: :cascade do |t|
t.string "email"
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.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "admins", ["confirmation_token"], name: "index_admins_on_confirmation_token", unique: true
add_index "admins", ["email"], name: "index_admins_on_email", unique: true
add_index "admins", ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true
create_table "answers", force: :cascade do |t|
t.integer "number"
t.text "content"
t.boolean "correct", default: false, null: false
t.integer "answerable_id"
t.string "answerable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "answers", ["answerable_type", "answerable_id"], name: "index_answers_on_answerable_type_and_answerable_id"
create_table "categories", force: :cascade do |t|
t.string "name"
t.integer "subject_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "categories", ["category_id"], name: "index_categories_on_category_id"
add_index "categories", ["subject_id"], name: "index_categories_on_subject_id"
create_table "choices", force: :cascade do |t|
t.string "content"
t.integer "quiz_part_id"
t.integer "answer_id"
t.boolean "correct"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "choices", ["answer_id"], name: "index_choices_on_answer_id"
add_index "choices", ["quiz_part_id"], name: "index_choices_on_quiz_part_id"
create_table "ckeditor_assets", force: :cascade do |t|
t.string "data_file_name", null: false
t.string "data_content_type"
t.integer "data_file_size"
t.integer "assetable_id"
t.string "assetable_type", limit: 30
t.string "type", limit: 30
t.integer "width"
t.integer "height"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "ckeditor_assets", ["assetable_type", "assetable_id"], name: "idx_ckeditor_assetable"
add_index "ckeditor_assets", ["assetable_type", "type", "assetable_id"], name: "idx_ckeditor_assetable_type"
create_table "levels", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "question_categories", force: :cascade do |t|
t.integer "question_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "question_categories", ["category_id"], name: "index_question_categories_on_category_id"
add_index "question_categories", ["question_id"], name: "index_question_categories_on_question_id"
create_table "question_parts", force: :cascade do |t|
t.text "content"
t.string "type"
t.integer "question_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
end
add_index "question_parts", ["deleted_at"], name: "index_question_parts_on_deleted_at"
add_index "question_parts", ["question_id"], name: "index_question_parts_on_question_id"
create_table "questions", force: :cascade do |t|
t.text "content"
t.string "type"
t.integer "level_id"
t.integer "subject_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
t.string "source"
end
add_index "questions", ["deleted_at"], name: "index_questions_on_deleted_at"
add_index "questions", ["level_id"], name: "index_questions_on_level_id"
add_index "questions", ["subject_id"], name: "index_questions_on_subject_id"
create_table "quiz_categories", force: :cascade do |t|
t.integer "category_id"
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "quiz_categories", ["category_id"], name: "index_quiz_categories_on_category_id"
add_index "quiz_categories", ["quiz_id"], name: "index_quiz_categories_on_quiz_id"
create_table "quiz_parts", force: :cascade do |t|
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "answerable_id"
t.string "answerable_type"
end
add_index "quiz_parts", ["answerable_type", "answerable_id"], name: "index_quiz_parts_on_answerable_type_and_answerable_id"
add_index "quiz_parts", ["quiz_id"], name: "index_quiz_parts_on_quiz_id"
create_table "quizzes", force: :cascade do |t|
t.integer "user_id"
t.datetime "completed_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "subject_id"
t.integer "number_of_questions"
end
add_index "quizzes", ["subject_id"], name: "index_quizzes_on_subject_id"
add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id"
create_table "subjects", force: :cascade do |t|
t.string "name"
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 "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 "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
I believe you are using wrong quotes:
SELECT COUNT(*) ....... (`question_categories`.`category_id` IN (87,1))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Use " " instead of ``
Update:
Yep, I have been right in your quiz model you're using wrong quotes:
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('`question_categories`.`category_id` IN (?)', category_ids)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Fix it to:
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('"question_categories"."category_id" IN (?)', category_ids)
^^^^^^^^^^^^^^^^^^^^^