I want to create a new jobdescription with company_id from the current user, but it doesn't work, I tried different ways and it's still not working.
So, I don't know how to build the query in my controller, if you can tell me where the issue is, that would be very kind of you. Thanks.
Schema.rb
ActiveRecord::Schema.define(version: 20150212182839) do
create_table "companies", force: true do |t|
t.string "company_name"
t.string "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "jobdescriptions", force: true do |t|
t.string "applyjobid"
t.string "job_title"
t.string "department"
t.text "shift"
t.string "work_location"
t.string "position_supervisor"
t.string "supervisor_position_supervisor"
t.decimal "rate_pay"
t.text "benefits"
t.text "other_benefits"
t.text "job_summary"
t.text "job_duties"
t.text "tasks"
t.text "results"
t.text "responsibilities"
t.text "knowledge"
t.text "skills"
t.text "abilities"
t.text "physical_requirement"
t.text "work_envir_condition"
t.text "protective_clothing_and_devices_required"
t.text "tools_or_equipment_required"
t.text "qualifications"
t.text "education_and_training"
t.text "license_certification"
t.text "experience"
t.text "aptitudes_interests_temperament"
t.text "roles_relationships"
t.text "supervisory_responsibility"
t.text "advancement_promotion_opportunities"
t.string "internal_comment"
t.string "submited_by"
t.string "approved_by"
t.string "statut"
t.date "from_date"
t.date "end_date"
t.integer "company_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "jobdescriptions", ["company_id"], name: "index_jobdescriptions_on_company_id"
create_table "users", force: true do |t|
t.string "username"
t.string "country"
t.string "role_id"
t.integer "company_id"
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.integer "current_sign_in_ip"
t.integer "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["company_id"], name: "index_users_on_company_id"
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
create_table "users_roles", id: false, force: true do |t|
t.integer "user_id"
t.integer "role_id"
end
add_index "users_roles", ["user_id", "role_id"], name: "index_users_roles_on_user_id_and_role_id"
end
Here is my JobdescriptionsController
class JobdescriptionsController < ApplicationController
layout 'application'
def new
#jobdescription = Jobdescription.new
end
def create
#jobdescription = current_user.company_id.jobdescriptions.create(jobdescription_params)
redirect_to new_jobdescription_path
end
private
def jobdescription_params
params.require(:jobdescription).permit(:applyjobid, :job_title, :work_location, :rate_pay, :shift, )
end
end
Model Jobdescription
class Jobdescription < ActiveRecord::Base
belongs_to :company
end
Model Company
class Company < ActiveRecord::Base
has_many :users
has_many :jobdescriptions
end
Model User
class User < ActiveRecord::Base
rolify
default_value_for :role_id, "1"
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :timesheets
has_many :expenses
belongs_to :company
end
I think the problem is that current_user.company_id gives the integer value of the company_id for that user's company, when what you actually want is to get the company object instance itself. Then you can call create on that company instance.
So the assignment for #jobdescription in the create method would be:
#jobdescription = current_user.company.jobdescriptions.create(jobdescription_params)
Related
I created the following Active Record Schema using migrations but the relationships don't correspond to the schema. I've tried resetting, dropping, creating and migrating but in Rails C if i create a User u.User.create!(...), and then query u.groups or u.genres I get 'undefined method'
Thanks for your help
ActiveRecord::Schema.define(version: 20180603211047) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "genres", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "tag"
t.bigint "user_id"
t.index ["user_id"], name: "index_genres_on_user_id"
end
create_table "genres_users", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "genre_id", null: false
end
create_table "groups", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.bigint "user_id"
t.index ["user_id"], name: "index_groups_on_user_id"
end
create_table "groups_users", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "group_id", null: false
end
create_table "playlists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "link"
t.text "description"
t.bigint "group_id"
t.index ["group_id"], name: "index_playlists_on_group_id"
end
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
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.string "name"
t.string "token"
t.date "birthday"
t.string "link"
t.string "playlistId"
t.string "country"
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 "genres", "users"
add_foreign_key "groups", "users"
add_foreign_key "playlists", "groups"
end
here are the models:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#before_action :authenticate_user!
has_and_belongs_to_many :genres, :through => :genres_users
has_and_belongs_to_many :groups, :through => :groups_users
include Enumerable
end
class Genre < ApplicationRecord
has_and_belongs_to_many :users, :through => :genres_users
end
class Group < ApplicationRecord
has_and_belongs_to_many :users, :through => :groups_users
has_one :playlist
end
class Playlist < ApplicationRecord
belongs_to :group
end
The relationship is that Groups have users, users have genres (favourite genres!), these are has and belongs to relationships through join tables (multiple genres per user and multiple groups per user). Every group has a playlist, and there will be multiple playlists
[Edited after clarification from OP]
The relationship is that Groups have users, users have genres (favourite genres!), these are has and belongs to relationships through join tables (multiple genres per user and multiple groups per user). Every group has a playlist, and there will be multiple playlists
First off, you don't need a user_id column on groups or genres as that's not how the setup should work.
class Genre < ApplicationRecord
has_many :favorite_genres
has_many :users, through: :favorite_genres
[... other stuff]
end
class User < ApplicationRecord
has_many :group_memberships
has_many :groups, through: :group_memberships
has_many :favorite_genres
has_many :users, through: :favorite_genres
[... other stuff]
end
class Group < ApplicationRecord
has_many :group_memberships
has_many :users, through: :group_memberships
has_many :playlists
[... other stuff]
end
class Playlist < ApplicationRecord
belongs_to :group
end
class GroupMemberships < ApplicationRecord
belongs_to :user
belongs_to :group
[... other stuff]
end
class FavoriteGenres < ApplicationRecord
belongs_to :user
belongs_to :genre
[... other stuff]
end
So you'd drop the user_id column in groups. The connection happens in :group_memberships (the table formerly known as users_groups), which is a user_id, a group_id, and then you can have additional metadata columns as you need them (e.g. admin boolean/role, etc)
. This is called a "Has Many Through" relationship (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)
Likewise, a user's favorite genres is setup with a through relationship. So you'll have a separate database table AND model file for those through joins.
I don't think you need your add_foreign_key calls at all at this level, nor many of your indexes. You'll probably do more eager loading or possibly add indexes on the thorugh join tables and you'd do those like this in the schema:
t.index ["user_id", "genre_id"], name: "index_favorite_genres_on_user_id_and_genre_id"
Remember that belongs_to now creates a validation for that to be present in 5.x. You can override this by adding optional: true on that line in the model, e.g. belongs_to :foo, optional: true
So all that being said, here's your new schema:
create_table "genres", id: :serial, force: :cascade do |t|
t.string "tag"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "groups", id: :serial, force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "favorite_genres", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "genre_id", null: false
end
create_table "groups_memberships", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "group_id", null: false
end
create_table "playlists", id: :serial, force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "link"
t.text "description"
t.bigint "group_id"
t.index ["group_id"], name: "index_playlists_on_group_id"
end
create_table "users", id: :serial, force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
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.string "name"
t.string "token"
t.date "birthday"
t.string "link"
t.string "playlistId"
t.string "country"
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
Give that a whirl (I haven't built this in an app, so there may be some errors in the code) and you should now be able to do your console run:
u = User.create([values])
u.genres (should return nil until you create some relationships)
etc.
I'm trying to deploy my app for the first time in heroku and I'm encountering a weird bug. When I try to run heroku rake db:migrate, i see this error :
rake aborted! StandardError: An error has occurred, this and all later
migrations canceled:
PG::UndefinedTable: ERROR: relation "companies" does not exist
: CREATE TABLE "users" ("id" bigserial primary key, "admin" boolean DEFAULT 'f', "admin_c" boolean DEFAULT 'f', "color" character varying, "initial" character varying, "name" character varying, "surname" character varying, "pseudo" character varying, "step" integer, "company_id" bigint, "email" character varying DEFAULT '' NOT NULL, "encrypted_password" character varying DEFAULT '' NOT NULL, "reset_password_token" character varying, "reset_password_sent_at" timestamp, "remember_created_at" timestamp, "sign_in_count" integer DEFAULT 0 NOT NULL, "current_sign_in_at" timestamp, "last_sign_in_at" timestamp, "current_sign_in_ip" character varying, "last_sign_in_ip" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_7682a3bdfe"
FOREIGN KEY ("company_id")
REFERENCES "companies" ("id")
)
I have verified a thousand times my migrations files Users & Companies but nothing seems bad. So I really don't know what to do. I also try all the database reset etc..
Like in this answer for example. But nothing is working for me. Anyone have seen this before ?? I'm really desperate at this point.
PS: And I also remove made the pg and sql3 changes.
So I give you my code if it can be useful to discover the problem
Company_model :
class Company < ApplicationRecord
has_many :users, dependent: :destroy
has_many :groups, dependent: :destroy
end
User_model :
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :company, optional: true
has_many :users_group, dependent: :destroy
has_many :groups, through: :users_group
has_many :users_post, dependent: :destroy
has_many :posts, through: :users_post
has_many :tasks_users, dependent: :destroy
has_many :tasks, through: :tasks_users
has_many :requests, dependent: :destroy
has_many :groupes_admin, dependent: :destroy
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :tasks, dependent: :destroy
end
Company migration :
class CreateCompanies < ActiveRecord::Migration[5.1]
def change
create_table :companies do |t|
t.string :name
t.string :ref
t.timestamps
end
end
end
Devise migration :
class DeviseCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
## Database authenticatable
t.boolean :admin, default: false
t.boolean :admin_c, default: false
t.string :color
t.string :initial
t.string :name
t.string :surname
t.string :pseudo
t.integer :step
t.references :company, index: true, foreign_key: true
t.boolean :admin, default: false
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
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.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
end
end
Schema :
ActiveRecord::Schema.define(version: 20170727071936) do
create_table "comments", force: :cascade do |t|
t.string "content"
t.boolean "done"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_comments_on_post_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "companies", force: :cascade do |t|
t.string "name"
t.string "ref"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "groupes_admins", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.index ["group_id"], name: "index_groupes_admins_on_group_id"
t.index ["user_id"], name: "index_groupes_admins_on_user_id"
end
create_table "groups", force: :cascade do |t|
t.string "name"
t.integer "cat"
t.boolean "main"
t.boolean "perso"
t.integer "effectif", default: 0
t.integer "elm", default: 0
t.integer "elm_d", default: 0
t.integer "date_cat"
t.integer "date_id"
t.datetime "date"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["company_id"], name: "index_groups_on_company_id"
end
create_table "posts", force: :cascade do |t|
t.text "content"
t.boolean "attached"
t.integer "attached_cat"
t.integer "attached_id"
t.boolean "done"
t.datetime "done_at"
t.integer "done_cat"
t.integer "donner_id"
t.datetime "upd_at"
t.integer "upd_cat"
t.integer "updater_id"
t.string "title"
t.date "deadline"
t.integer "group_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_id"], name: "index_posts_on_group_id"
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "requests", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.datetime "validate_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_id"], name: "index_requests_on_group_id"
t.index ["user_id"], name: "index_requests_on_user_id"
end
create_table "subtasks", force: :cascade do |t|
t.string "title"
t.datetime "date"
t.boolean "finished"
t.datetime "done_at"
t.integer "done_id"
t.integer "assign_id"
t.integer "task_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["task_id"], name: "index_subtasks_on_task_id"
end
create_table "tasks", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.integer "post_id"
t.string "title"
t.datetime "date"
t.boolean "done"
t.integer "doner_id"
t.datetime "done_at"
t.boolean "assigned"
t.integer "elm", default: 0
t.integer "elm_d", default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_id"], name: "index_tasks_on_group_id"
t.index ["post_id"], name: "index_tasks_on_post_id"
t.index ["user_id"], name: "index_tasks_on_user_id"
end
create_table "tasks_users", force: :cascade do |t|
t.integer "task_id"
t.integer "user_id"
t.index ["task_id"], name: "index_tasks_users_on_task_id"
t.index ["user_id"], name: "index_tasks_users_on_user_id"
end
create_table "users", force: :cascade do |t|
t.boolean "admin", default: false
t.boolean "admin_c", default: false
t.string "color"
t.string "initial"
t.string "name"
t.string "surname"
t.string "pseudo"
t.integer "step"
t.integer "company_id"
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.index ["company_id"], name: "index_users_on_company_id"
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
create_table "users_groups", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.index ["group_id"], name: "index_users_groups_on_group_id"
t.index ["user_id"], name: "index_users_groups_on_user_id"
end
create_table "users_posts", force: :cascade do |t|
t.integer "post_id"
t.integer "user_id"
t.index ["post_id"], name: "index_users_posts_on_post_id"
t.index ["user_id"], name: "index_users_posts_on_user_id"
end
end
The error message suggests that you're trying to create a reference to companies on the users table but the companies table doesn't yet exist. Try making sure the order of your migrations is such that companies is created before users. You can also try just loading the schema all at once rather than migrating one at a time, with heroku run rake db:schema:load.
DISCLAIMER: rake db:schema:load will wipe all of your data. It is best used for setting up a new database. Never run it against a production database that already contains critical data. Once you have data you will need to do incremental migrations.
Create the database first with rake db:create.
Hello I'm getting a rollback transaction when I try to create a Bid from the rails console. These are my models:
Product Model
class Product < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :ratings
has_many :bids
end
Bid model:
class Bid < ApplicationRecord
belongs_to :products
belongs_to :user
end
User model:
class User < ApplicationRecord
has_many :products
has_many :ratings
has_many :bids
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
And this is my schema:
ActiveRecord::Schema.define(version: 20161231124005) do
create_table "bids", force: :cascade do |t|
t.integer "amount"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "product_id"
t.index ["product_id"], name: "index_bids_on_product_id"
t.index ["user_id"], name: "index_bids_on_user_id"
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.integer "price"
t.datetime "deadline"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "category_id"
end
create_table "ratings", force: :cascade do |t|
t.integer "rating"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "product_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
t.string "username"
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 ["username"], name: "index_users_on_username", unique: true
end
end
Although I tried to create like so: Bid.create(amount: 500, user_id: 1, product_id:6) it doesn't save because of the rollback transaction.
Thanks in advance
The code you posted doesn't really help. You should also add the logs.
Before posting any logs, I'd try b = Bid.new(amount: 500, user_id: 1, product_id: 6) and b.save in the console. After that, do b.errors and see what's causing the rollback.
EDIT: Add .save.
EEDIT: For anyone experiencing the same problem, the issue was with the Bid model referencing a Product wrong.
When using belongs_to, the model should be singular, not plural. Ex: belongs_to: apple not belongs_to: apples
This line raises the error "wrong number of arguments (given 1, expected 0)". I would really like to know how to get this query to work. Thanks!
#posts = Post.all(:joins => :course, :conditions => "course.name in (#{#user.courses.map(&:name).join(',')})",:order => "posts.created_at DESC")
This is code in my controller:
#user = current_user
#posts = Post.all(:joins => :course, :conditions => "course.name in (#{#user.courses.map(&:name).join(',')})",:order => "posts.created_at DESC")
Here are the models:
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :course
has_many :comments
end
class Course < ActiveRecord::Base
belongs_to :user
has_many :posts
belongs_to :major
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_many :courses
belongs_to :major
has_many :posts
has_many :comments
accepts_nested_attributes_for :courses, reject_if: :all_blank, allow_destroy: true
end
And here is the schema
create_table "comments", force: :cascade do |t|
t.text "comment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "post_id"
end
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
add_index "comments", ["user_id"], name: "index_comments_on_user_id"
create_table "courses", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "major_id"
t.integer "user_id"
end
add_index "courses", ["major_id"], name: "index_courses_on_major_id"
add_index "courses", ["user_id"], name: "index_courses_on_user_id"
create_table "majors", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "course_id"
end
add_index "posts", ["course_id"], name: "index_posts_on_course_id"
add_index "posts", ["user_id"], name: "index_posts_on_user_id"
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"
t.string "username"
t.integer "major_id"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["major_id"], name: "index_users_on_major_id"
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
add_index "users", ["username"], name: "index_users_on_username", unique: true
end
The error you are getting in the query is due to the fact that the all method does not expect any parameters, it just retrieves all records for a given model/relation.
What you want to use in this case is the where method from ActiveRecord::QueryMethods.
There is another error, you are using the name of the table in singular on your condition, where it should be plural (courses instead of course).
Also, you could use here the includes method combined with the references method to generate the database join.
So, you would have something like the following:
#posts = Post.includes(:course).where("courses.name IN (#{#user.courses.map(&:name).collect { |s| '#{s}' }.join(',') })").references(:courses).order("posts.created_at DESC")
I have some problem. I want to show the best hotels on page 5, but I do not know how to do it. I maintenance used gem letsrate.
schema.rb
create_table "hotels", force: true do |t|
t.string "title"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
t.string "author"
t.boolean "breakfast"
t.decimal "price"
t.string "avatar"
t.integer "address_id"
end
create_table "rates", force: true do |t|
t.integer "rater_id"
t.integer "rateable_id"
t.string "rateable_type"
t.float "stars", null: false
t.string "dimension"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "rates", ["rateable_id", "rateable_type"], name: "index_rates_on_rateable_id_and_rateable_type"
add_index "rates", ["rater_id"], name: "index_rates_on_rater_id"
create_table "rating_caches", force: true do |t|
t.integer "cacheable_id"
t.string "cacheable_type"
t.float "avg", null: false
t.integer "qty", null: false
t.string "dimension"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "rating_caches", ["cacheable_id", "cacheable_type"], name: "index_rating_caches_on_cacheable_id_and_cacheable_type"
create_table "users", force: true 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
rate.rb
class Rate < ActiveRecord::Base
belongs_to :rater, :class_name => "User"
belongs_to :rateable, :polymorphic => true
#attr_accessible :rate, :dimension
end
hotel.rb
class Hotel < ActiveRecord::Base
belongs_to :user
belongs_to :address
letsrate_rateable 'Rating'
mount_uploader :avatar, AvatarUploader
accepts_nested_attributes_for :address
end
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
letsrate_rater
has_many :hotels
end
Please
I know how to do this using sql query, but I just started learning RoR and I'm sure there are more elegant way that someone can suggest?
First you have to change the dimension name to be downcased, otherwise it wouldn't map to your table names and the uppecase relation names this gem generated wouldn't follow rails conventions.
#Hotel
letsrate_rateable 'rating'
To show top n hotels by rating, run
Hotel.includes(:rating_average).order("rating_caches.avg DESC").limit(n)
You have to also add an index to the avg field in rating_caches
Have also a look on letsrate_rateable method. It just defines some associations based on the dimnesion names