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
Related
Basically working on setting up a favorite product situation but I'm stuck on actually setting it up
This is what I got so far
I think it's because I'm using Friendly URL - I've added friendly.find.. but I still get another error there as well (see second image)
Controller
def update
khollection = Khollection.where(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
if khollection == []
# Create the khollection
Khollection.create(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
#khollection_exists = true
else
# Delete the khollection
khollection.destory_all
#khollection_exists = false
end
respond_to do |format|
format.html {}
format.js {}
end
end
View
<%= link_to 'Favorite', khollections_update_path(cproduct: #cproduct.title) %>
Below With Friendly .friendly.find(params...
def update
khollection = Khollection.where(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
if khollection == []
# Create the khollection
Khollection.create(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
MODEL
class Khollection < ApplicationRecord
belongs_to :cproduct
belongs_to :user
end
Schema.rb
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_05_28_112623) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "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.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "cproducts", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.string "slug"
t.index ["slug"], name: "index_cproducts_on_slug", unique: true
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 "khollections", force: :cascade do |t|
t.integer "Cproduct_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
t.index ["user_id"], name: "index_khollections_on_user_id"
end
create_table "users", 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.text "full_company_logo"
t.text "domain"
t.string "business_name"
t.string "tags"
t.text "social_media"
t.text "our_story"
t.text "location_address"
t.string "location_city"
t.string "location_state"
t.integer "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "admin"
t.boolean "company"
t.boolean "judge"
t.boolean "blogger"
t.string "username"
t.string "slug"
t.string "avatar"
t.string "company_logo"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["slug"], name: "index_users_on_slug", unique: true
end
end
CURRENT ERROR
this is where error is
create_table "khollections", force: :cascade do |t|
t.integer "Cproduct_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
t.index ["user_id"], name: "index_khollections_on_user_id"
end
replace with
create_table "khollections", force: :cascade do |t|
t.integer "cproduct_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["cproduct_id"], name: "index_khollections_on_cproduct_id"
t.index ["user_id"], name: "index_khollections_on_user_id"
end
and
khollection = Khollection.where(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)
Khollection.create(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)
<%= link_to 'Favorite', khollections_update_path(cproduct: #cproduct.title) %>
Not sure what's going on behind the scenes with the friendly id, but you should be able to query by the product name:
product = Cproduct.find_by(title: params[:cproduct]).take
if product
khollection = Khollection.where(cproduct_id: product.id), user: current_user).take
if khollection.blank?
# Create the khollection
Khollection.create(cproduct: product, user: current_user)
#khollection_exists = true
else
# Delete the khollection
khollection.destory_all
#khollection_exists = false
end
else
# maybe return an error status "Product not found"
end
respond_to do |format|
format.html {}
format.js {}
end
The point is that you can always fall back on the column names instead of relying on a gem.
So I'm trying to use appointments gem (http://www.rubydoc.info/gems/appointments/1.3.3). I've done exactly as that document says and I keep getting the following error:
ActiveRecord::StatementInvalid in AppointmentsController#index
SQLite3::SQLException: no such column: appointments.date: SELECT "appointments".* FROM "appointments" WHERE "appointments"."date" IS NULL
app/controllers/appointments_controller.rb:6:in `index'
schema.rb
ActiveRecord::Schema.define(version: 20180402162908) do
create_table "appointments", force: :cascade do |t|
t.datetime "appointment_time"
t.integer "duration"
t.float "price"
t.integer "user_id"
t.integer "client_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "appointments", ["client_id"], name: "index_appointments_on_client_id"
add_index "appointments", ["user_id"], name: "index_appointments_on_user_id"
create_table "clients", force: :cascade do |t|
t.string "name"
t.string "phone_number"
t.string "email"
t.string "address"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "clients", ["user_id"], name: "index_clients_on_user_id"
create_table "services", force: :cascade do |t|
t.string "name"
t.string "description"
t.float "price"
t.integer "duration"
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", 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
appointments_controller.rb
class AppointmentsController < ApplicationController
def index
date_from_ajax = params[:matched_date]
reduce = Appointment.where(:date => date_from_ajax)
hour_on_date = reduce.collect {|x| x.hour}
#new_dates = hour_on_date
render :layout => false
end
def new
#appointments = Appointment.create
respond_to do |format|
format.html
format.js
end
end
def create
#appointment = Appointment.create(params[:appointments])
if #appointment.save
redirect_to new_appointment_path
else
err = ''
#appointment.errors.full_messages.each do |m|
err << m
end
redirect_to new_appointment_path, :flash => { :alert => "#{err}, please try again" }
end
end
private
def appointment_params
params.require(:appointment).permit(:date, :hour, :done)
end
end
appointments.rb
class Appointment < ActiveRecord::Base
validates :date, :presence => true
validates :hour, :presence => true,
:uniqueness => {:scope => :date}
end
Is there any chance someone could help me with this.
Thanks in advance :)
(Rails version: 4.2.6)
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 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)
^^^^^^^^^^^^^^^^^^^^^
How can we combine all these resources into one feed, with the most recent submission showing at the top?
user.rb
# Returns status feed.
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Habit.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
Valuation.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
Goal.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
Quantified.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
schema.rb
ActiveRecord::Schema.define(version: 20150311202504) do
create_table "authentications", force: true do |t|
t.integer "user_id"
t.string "provider"
t.string "uid"
t.string "index"
t.string "create"
t.string "destroy"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "days", force: true do |t|
t.integer "level_id"
t.integer "habit_id"
t.boolean "missed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "goals", force: true do |t|
t.string "name"
t.date "deadline"
t.boolean "accomplished"
t.text "comment"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "goals", ["user_id", "created_at"], name: "index_goals_on_user_id_and_created_at"
add_index "goals", ["user_id"], name: "index_goals_on_user_id"
create_table "habits", force: true do |t|
t.datetime "left"
t.integer "level"
t.text "committed"
t.datetime "date_started"
t.string "trigger"
t.string "target"
t.string "reward"
t.text "comment"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "habits", ["user_id", "created_at"], name: "index_habits_on_user_id_and_created_at"
add_index "habits", ["user_id"], name: "index_habits_on_user_id"
create_table "levels", force: true do |t|
t.integer "user_id"
t.integer "habit_id"
t.integer "days_needed"
t.boolean "passed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "quantifieds", force: true do |t|
t.string "categories"
t.string "metric"
t.text "comment"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "quantifieds", ["user_id", "created_at"], name: "index_quantifieds_on_user_id_and_created_at"
add_index "quantifieds", ["user_id"], name: "index_quantifieds_on_user_id"
create_table "relationships", force: true do |t|
t.integer "follower_id"
t.integer "followed_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "relationships", ["followed_id"], name: "index_relationships_on_followed_id"
add_index "relationships", ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
add_index "relationships", ["follower_id"], name: "index_relationships_on_follower_id"
create_table "results", force: true do |t|
t.integer "user_id"
t.string "result_value"
t.date "date_value"
t.integer "quantified_id"
t.boolean "good"
t.text "comment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "taggings", force: true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context", limit: 128
t.datetime "created_at"
end
add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", force: true do |t|
t.string "name"
t.integer "taggings_count", default: 0
end
add_index "tags", ["name"], name: "index_tags_on_name", unique: true
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.text "missed_days"
t.text "missed_levels"
t.string "provider"
t.string "uid"
t.string "oauth_token"
t.datetime "oauth_expires_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
create_table "valuations", force: true do |t|
t.string "name"
t.text "comment"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "valuations", ["user_id", "created_at"], name: "index_valuations_on_user_id_and_created_at"
add_index "valuations", ["user_id"], name: "index_valuations_on_user_id"
end
pages_controller.rb
class PagesController < ApplicationController
def home
if logged_in?
#habits = current_user.habits.build
#valuations = current_user.valuations.build
#accomplished_goals = current_user.goals.accomplished
#unaccomplished_goals = current_user.goals.unaccomplished
#averaged_quantifieds = current_user.quantifieds.averaged
#instance_quantifieds = current_user.quantifieds.instance
#feed_items = current_user.feed.paginate(page: params[:page])
end
end
def about
end
end
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Thanks so much for your time! So far Infused's answer isn't working.
The simplest way to handle it is to combine the collections with +:
cond = ["user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id]
Habit.where(cond) + Valuation.where(cond) + Goal.where(cond) + Quantified.where(cond)
As Matt Brictson mentioned in a comment, there may be a better way to aggregate the various models, but simply using + to join the collections will do the trick.