I have one question regarding to time zone
I have done the following yet, my activerecord is not still matching with my timezone when I do following query
def stock_by_date(date)
UserStock.where("date(created_at) = ? and user_id = ? ", date , current_user.id)
end
I did the following in side my application.rb
config.active_record.default_timezone = :utc
config.active_record.time_zone_aware_attributes = true
config.beginning_of_week = :sunday
config.active_record.time_zone_aware_types = [:datetime, :time]
I added timezone field to my sign up method, and it shows the current day of timezone correctly, yet when I added a stock for the current day timezone, it shows up in either the previous day or next day of current daytime zone and when I added my stock, the timestamp is for a day before when I look at the rails console
My schema.rb
ActiveRecord::Schema.define(version: 2018_11_28_183416) do
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["friend_id"], name: "index_friendships_on_friend_id"
t.index ["user_id"], name: "index_friendships_on_user_id"
end
create_table "notes", force: :cascade do |t|
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.index ["user_id"], name: "index_notes_on_user_id"
end
create_table "stocks", force: :cascade do |t|
t.string "ticker"
t.string "name"
t.decimal "last_price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "user_stocks", force: :cascade do |t|
t.integer "user_id"
t.integer "stock_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["stock_id"], name: "index_user_stocks_on_stock_id"
t.index ["user_id"], name: "index_user_stocks_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "time_zone", default: "UTC"
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
end
for example,
How can I fix this issue?
Note: If more info is needed, please let me know
Note: for the matter of being concise this is my repo
Note: my configuration does not show a reliable behavior at all and I am very confused :/ and I have the same issue for note of a current day
----update-------------------
In my rails console
create a migration with this content to remove the default value to created_at, so it's not filled by default on database level.
change_column_default(:user_stocks, :created_at, nil)
after that, when you create a new UserStock, you need to specify the created_at value, and there you can specify the created_at with the date of the user, taking care of the timezone.
UserStock.create(created_at: Time.now.in_time_zone(user.time_zone).to_time...)
or you can just maybe add it to a callback on the model so it's automatic everytime you create a UserStock, it change the value
class UserStock < ActiveRecord::Base
before_create :set_created_at
private
def set_created_at
self.created_at = time.now.in_time_zone(self.user.time_zone).to_time
end
end
so everytime you create one, the value is correct. with that it may work as expected.
Another option if you don't need it just for that specific model and use them for all the user interaction, you can create a before filter on the application controller to set the time zone dinamically, something like
class ApplicationController < ActionController::Base
before_filter :set_time_zone
def set_time_zone(&block)
time_zone = current_user.try(:time_zone) || 'UTC'
Time.use_zone(time_zone, &block)
end
end
Did you try the query by specifying the range?
Because you're trying to find the user_stocks that are created on some date. But notice that created_at is a datetime object and I guess your date variable might be just a date object.
def stock_by_date(date)
UserStock.where(created_at: date.midnight..date.end_of_day, user_id: current_user.id)
end
Related
I've just start to creating new app from scratch and call a Pocket model from this controller:
class HomeController < ApplicationController
def index
end
def wallets_index
end
def wallets_show
end
def wallets_new
#pocket = Pocket.new
end
end
and this odd error appeared:
transaction is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name.
my schema:
create_table "pockets", force: :cascade do |t|
t.string "address"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "transaction"
t.index ["user_id"], name: "index_pockets_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
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 "pockets", "users"
And Pocket model:
class Pocket < ApplicationRecord
belongs_to :user
end
This is actually the first time that happened to me and I have no idea which attribute should I rename in order to avoid conflicts?
You are using the transaction column in your Pocket model
t.integer "transaction"
I would suggest against using a column which has a similar name to a rails method. The transaction method is defined in transcations.rb module of Rails
But, if you really want to use it, you can check safe_attributes gem.
In your pockets table or migration, transaction is a reserved word, so you cannot use that word.
First stack overflow question, so I apologize ahead of time for forgetting things.
Project:
Announcement Feature, which allows admin / moderators to post announcements on website.
Tools/Languages Used:
React / Ruby on Rails, Devise (for login)
History:
The announcement feature was UP and RUNNING; until I added a "Username" field to my Announcement table. I properly updated the migration/schema, and made adjustments to the controller, to permit the new field, as well as the React form, to pass the new field into the announcements object.
Error:
After updating migration/schema files with new fields, updating announcement_controller to permit the new field, and updating the React form to capture and POST the new "Announcement" object through an AXIOS POST request, I get the following error: "Filter chain halted as :authenticate_user! rendered or redirected" 401 unauthorized, etc.
Things I've Tried So Far:
I've verified all the data the SHOULD be in the announcement object, just before being pushed through the POST request, is where it should be. (See images below)
I tried using a Binding.Pry, which works like Javascript's "Debugger" except for Ruby, but my binding.pry wasn't stopping ANYWHERE in the announcements controller, which leads me to believe the POST request isn't even making it to the announcements_controller before the error below.
I've verified the Announcements table is what it should be.
I've set the new field to to be permitted in the announcement_controller
Code Examples / Images:
handleSubmit POST request
handleSubmit = (announcement) => { axios.post(`/api/announcements`, announcement)}
Contents of "announcement" JUST before being passed into handleSubmit()
Filter Chain Halted as :authenticate_user! rendered or redirect: Error Message AFTER POST request
Announcements schema / database / table
ActiveRecord::Schema.define(version: 2018_12_19_224825) do
# These are extensions that must be enabled in order to support this
database
enable_extension "plpgsql"
create_table "accounts", force: :cascade do |t|
t.string "account_name"
t.bigint "users_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["users_id"], name: "index_accounts_on_users_id"
end
create_table "announcements", force: :cascade do |t|
t.string "body"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_announcements_on_user_id"
end
create_table "games", force: :cascade do |t|
t.string "game_name"
t.bigint "accounts_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["accounts_id"], name: "index_games_on_accounts_id"
end
create_table "team_has_tournaments", force: :cascade do |t|
t.bigint "tournament_id"
t.bigint "team_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["team_id"], name: "index_team_has_tournaments_on_team_id"
t.index ["tournament_id"], name: "index_team_has_tournaments_on_tournament_id"
end
create_table "teams", force: :cascade do |t|
t.string "team_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "tournaments", force: :cascade do |t|
t.text "tournament_description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "tournament_name"
end
create_table "user_has_teams", force: :cascade do |t|
t.bigint "user_id"
t.bigint "team_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["team_id"], name: "index_user_has_teams_on_team_id"
t.index ["user_id"], name: "index_user_has_teams_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "provider", default: "email", null: false
t.string "uid", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.boolean "allow_password_change", default: false
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.string "unconfirmed_email"
t.string "firstName"
t.string "lastName"
t.string "username"
t.string "image"
t.string "email"
t.json "tokens"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "level", default: 1
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
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 ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true
end
add_foreign_key "accounts", "users", column: "users_id"
add_foreign_key "announcements", "users"
add_foreign_key "games", "accounts", column: "accounts_id"
add_foreign_key "team_has_tournaments", "teams"
add_foreign_key "team_has_tournaments", "tournaments"
add_foreign_key "user_has_teams", "teams"
add_foreign_key "user_has_teams", "users"
end
Announcements controller that should be handling POST request (1)
Announcements controller that should be handling POST request (2)
class Api::AnnouncementsController < ApplicationController
before_action :set_announcement, only: [:show, :update, :destroy]
def index
render json: Announcement.all.order("created_at DESC")
end
def show
render json: #announcement
end
def new
#announcement = Announcement.new
end
def edit
end
def create
announcement = Announcement.new(announcement_params)
if announcement.save
render json: build_announcement(announcement)
else
render json: announcement.errors, status: 422
end
end
def update
if #announcement.update(announcement_params)
render json: #announcement
else
render json: #announcement.errors, status: 422
end
end
def destroy
#announcement.destroy
end
private
def build_announcement(announcement)
{
id: announcement.id,
body: announcement.body,
username: announcement.username,
user_id: announcement.user_id,
created_at: announcement.created_at,
updated_at: announcement.updated_at,
}
end
def set_announcement
#announcement = Announcement.find(params[:id])
end
def announcement_params
params.require(:announcement).permit(:body, :username, :user_id)
end
end
I note that your console output includes:
User Load (50.0ms) SELECT "users".* FROM "users" WHERE "users"."uid" = $1 LIMIT $2 [["uid", "admin#admin.com"], ["LIMIT", 1]]
(notwithstanding any typing errors on my part.)
It appears that you are trying to find the user with a uid of admin#admin.com. In your comments (deleted now, I think), you had said that you don't have such a user. If that's the case, then I assume that is what's causing your:
Filter chain halted as :authenticate_user! rendered or redirected
I think I would start with researching that bit.
I have a column/foreign key, resolver_id, that I want to be able to have null values (ie: Rails Migration to make a column null => true). Let's say I have the following line in my migration:
def
change_column_null :bugs, :resolver_id, true
end
However, after running a successful migration (ie, generate the migration and run rails db:migrate), the schema remains unchanged, besides the version number:
t.integer "resolver_id"
whereas I am expecting:
t.integer "resolver_id" , null: true
Is there something I'm missing?
I've also tried using just change_column like so:
change_column :bugs, :resolver_id, :integer, null: true
However, this is still not reflected in the schema. The rails g migration and db:migrate work just fine, and the version number in the schema matches the latest migration.
For reference, here is my schema:
ActiveRecord::Schema.define(version: 20170502203934) do
create_table "bugs", force: :cascade do |t|
t.string "name"
t.text "error_msg"
t.text "description"
t.text "causes"
t.boolean "resolved"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "resolver_id"
t.index ["resolver_id"], name: "index_bugs_on_resolver_id"
t.index ["user_id"], name: "index_bugs_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "first_name"
t.string "last_name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
end
If relevant, the resolver_id foreign key is a reference a User model, ie:
class Bug < ApplicationRecord
# Associations
belongs_to :user
belongs_to :resolver, class_name: 'User'
end
null: true is the default behavior. You will never see it in your schema, you will see either null: false or nothing.
I used the rails globalize and I18n gem. But now I can't sort my model. Can you guys help?
I tried adding a new index, but I'm not entirely familiar with indexing.
Controller.rb
def index
#foods = Food.all.order(:name)
add_breadcrumb "index", foods_path
end
Schema
create_table "food_translations", force: :cascade do |t|
t.integer "food_id", null: false
t.string "locale", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "bio"
end
add_index "food_translations", ["food_id"], name: "index_food_translations_on_food_id", using: :btree
add_index "food_translations", ["locale"], name: "index_food_translations_on_locale", using: :btree
add_index "food_translations", ["name"], name: "index_food_translations_on_name", using: :btree
create_table "foods", force: :cascade do |t|
t.string "address"
t.string "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.string "yelp"
t.string "youtube"
end
Yes, you will need a join. If you do not have a model for the translation, you could just use .joins for your finder. Like:
Food.joins('INNER JOIN food_translations ON foods.id=food_translations.food_id')
.order('food_translations.name').where('food_translations.locale=xxx')
ps: I wonder why you do not have a index on "food_id" AND "locale" which should be uniq. In your case you can have two or more translations for 1 food in the same language.
I have
class Article < ActiveRecord::Base
has_one :template
end
and
class Template < ActiveRecord::Base
has_many :articles
end
where Template model has got a room property. Now i'd like to build a list of all articles, where the articles template has a certain room value (say "bath").
I thought this is done by eager loading (resp: includes), but if i try
Article.includes(:template)
I get the error
SELECT "templates".* FROM "templates" WHERE "templates"."article_id" IN ('51', '52', '53', '54')
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column templates.article_id does not exist
LINE 1: SELECT "templates".* FROM "templates" WHERE "templates"."art...
What am I doing wrong?
EDIT
here's my schema.rb as asked
# encoding: UTF-8
# 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: 20160913122551) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "details"
t.integer "value_eur"
t.integer "deposit_eur"
t.integer "location_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "picture"
t.float "rate_eur"
t.string "rate_interval"
t.integer "template_id"
t.integer "quality"
end
add_index "articles", ["location_id"], name: "index_articles_on_location_id", using: :btree
add_index "articles", ["template_id"], name: "index_articles_on_template_id", using: :btree
add_index "articles", ["user_id"], name: "index_articles_on_user_id", using: :btree
create_table "locations", force: :cascade do |t|
t.string "street_and_no"
t.string "postcode"
t.string "city"
t.string "country"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "latitude"
t.float "longitude"
end
add_index "locations", ["user_id"], name: "index_locations_on_user_id", using: :btree
create_table "templates", force: :cascade do |t|
t.string "title"
t.text "details_hint"
t.float "rate_eur"
t.string "rate_interval"
t.string "picture"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "room"
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.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 "role"
t.string "nickname"
t.string "firstname"
t.string "lastname"
t.string "phoneno"
t.boolean "showemail"
t.boolean "showphone"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["nickname"], name: "index_users_on_nickname", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_foreign_key "articles", "locations"
add_foreign_key "articles", "templates"
add_foreign_key "articles", "users"
add_foreign_key "locations", "users"
end
Your templates table does not have an article_id column according to the schema.rb you posted so you will need to create that reference.
Change
has_one :template
in the articles model to
belongs_to :template