Recreating a table in Rails Posted: 24 Aug 2016 08:05 AM PDT I'm using Rails and Postgres. I currently have a Like table created. I need to drop this table and re-create it. Here's what I've done so far. 1) Rename create_likes migration file to create_likes_old so there is no conflict with file names within migrations. 2) Change the name of the table inside the migration from create_table :likes to create_table :likes_old . 3) Generate new create_likes migration that creates a table called Like. Currently I'm running into the following issue when I run rake db:migrate : PG::DuplicateTable: ERROR: relation "likes" already exists This makes it seems like the Like table was never renamed to LikeOld. What's wrong and how do I fix this? |
Rails validators: Only show certain messages based on hierarchy Posted: 24 Aug 2016 07:57 AM PDT For an email attribute, I have two validator helpers like so: validates :email, presence: true, format: { with: /some_regex/, message: "Bad email error message"} Is there a way to set this up (without using custom validator methods) so if presence: true fails, it will not display the format message? I don't want to display a format message when the field is blank...it doesn't present a nice user experience "of course it's a bad format... there's nothing there!" |
No routes matches DELETE for removing a CarrierWave multiple file uploader Posted: 24 Aug 2016 07:50 AM PDT Using a member route like this similar to one I have used for deleting tags: resources 'factory' do resources 'tags' do member do delete :remove end end resources 'project_files' do member do delete :remove end end end I (should) invoke in the projects controller: class ProjectFilesController < ApplicationController def remove @factory = Factory.find(params[:fabmoment_id]) @project_file = ProjectFile.find(params[:id]) authorize @factory, :project_file? @project_file.remove! head :ok end end Which I can't check for correctness (yet). The partial _project_files looks like: <li class="project_file"> <% if policy(factory).project_file? %> <%= link_to "<span></span>".html_safe, remove_factory_project_file_path(factory, project_file), method: :delete, remote: true, class: "remove", title: "remove" %> <% end %> <%= link_to File.basename(project_file.url), project_file.url %> (<%= number_to_human_size(project_file.file.size) %>) </li> Which is invoked by passing locales with a render method in the factory#show view. (Could also add an index.) Like this it is mostly equal to the tags remove action though and I like to keep things consequent and simple. The error I receive from my spec: No route matches [DELETE] "/factories/1/project_files/%2Fuploads%2Ffactory%2Fproject_files%2F1%2Fthe_puritan_1st_floor.stl/remove" My Factory model only contains mount_uploaders :project_files, ProjectFileUploader Any ideas on how to make this work? |
Upgrading Rails 3.2 to Rails 5 Posted: 24 Aug 2016 07:49 AM PDT I have a Rails 3.2 project that has 30 models and about 20 controllers. It's not a super huge codebase and its pretty much an idiomatic Rails site. Is there any advantage to just doing rails new and controller by controller, model by model, gem by gem just copy and pasting things in and getting everything running on a fresh Rails 5 instance? I just see some pain trying to do an upgrade version by version. Is this a viable way to upgrade a project where I have written all the code and know the project well? |
Ruby modify elements of nested hashes Posted: 24 Aug 2016 07:48 AM PDT I have a RoR application in which at some point I recieve some params in the form of a hash. There's a field amount repeated within the hash. I want the value of these fields inverted. This is an example of the nested hash: {"name"=>"asdasd", "rate_type"=>"DependantRate", "max_booking_anticipation"=>"5", "min_booking_anticipation"=>"5", "base_rate_id"=>"51", "category_rate_requests_attributes"=>{ "1472049336305"=>{ "mon"=>"1", "tue"=>"1", "wed"=>"1", "thu"=>"1", "fri"=>"1", "sat"=>"1", "sun"=>"1", "date_from"=>"2016-08-03", "date_to"=>"2016-08-03", "room_category_rates_attributes"=>{ "1472049336310"=>{"=>"7", "amount"=>"5"}, "1472049336314"=>{"room_category_id"=>"98", "amount"=>"15"}, "1472049336316"=>{"room_category_id"=>"3", "amount"=>"25"}, "1472049336320"=>{"room_category_id"=>"1", "amount"=>"35"}, "1472049336323"=>{"room_category_id"=>"115", "amount"=>"45"}, "1472049336325"=>{"room_category_id"=>"116", "amount"=>"55"}, "1472049336328"=>{"room_category_id"=>"117", "amount"=>"65"} } } }, "hotel_id"=>1} And I want to obtain a new hash which has that amount field with the same values but negative, as in: {"name"=>"asdasd", "rate_type"=>"DependantRate", "max_booking_anticipation"=>"5", "min_booking_anticipation"=>"5", "base_rate_id"=>"51", "category_rate_requests_attributes"=>{ "1472049336305"=>{ "mon"=>"1", "tue"=>"1", "wed"=>"1", "thu"=>"1", "fri"=>"1", "sat"=>"1", "sun"=>"1", "date_from"=>"2016-08-03", "date_to"=>"2016-08-03", "room_category_rates_attributes"=>{ "1472049336310"=>{"=>"7", "amount"=>"5"}, "1472049336314"=>{"room_category_id"=>"98", "amount"=>-15}, "1472049336316"=>{"room_category_id"=>"3", "amount"=>-25}, "1472049336320"=>{"room_category_id"=>"1", "amount"=>-35}, "1472049336323"=>{"room_category_id"=>"115", "amount"=>-45}, "1472049336325"=>{"room_category_id"=>"116", "amount"=>-55}, "1472049336328"=>{"room_category_id"=>"117", "amount"=>-65} } } }, "hotel_id"=>1} (yes, the values are now numbers but it doesn't really matter if they are strings or numbers as long as they are negative). This is what I've came up with: rate_params[:category_rate_requests_attributes].try(:each) do |_key1, category_rate_request| category_rate_request[:room_category_rates_attributes].each do |_key2, room_category_rate| room_category_rate[:amount] = room_category_rate[:amount].to_i * -1 end end But it's far from nice code. Any suggestions on what would be the best way to do this? |
Insert data in multiple level of embedding using rails in mongoid Posted: 24 Aug 2016 07:42 AM PDT I have one user which have many devices . Every device have many data. I am able to save multiple devices under my user. But how can i save data in my device using device._id. |
How to connect and authenticate an Android app to a Rails server? Posted: 24 Aug 2016 07:31 AM PDT I have and Android app that needs a chat application. I've opted to develop my chat application using Rails 5 and Action Cable (and it works just fine) and make my chat as a WebView in Android using Turbolinks 5 . My problem now is to connect my Android application to my Rails server. In Android I have Facebook and Google login. How can I pass my user information to Rails in order to authenticate and save them to the database and show their names and pictures in my Chat view? |
FormFor Behind the Scene - Model Field Validation without using FormFor Posted: 24 Aug 2016 07:51 AM PDT During code review, it was brought to my attention that I was using form_for for a form that contained fields that did not belong to the model. I never realised this was an issue, but they insist. The issue for me now is that they still want field validation to occur (i.e. model field presence validation). So far I've managed to achieve this using JS, looping through the errors key value pairs, selecting a field and highlighting it. I would like to know if there is another way of achieving the model validation or I would like to know how does front-end validation occur in Rails. |
Simple Form on Submit is not sending the input to MySQL Posted: 24 Aug 2016 07:16 AM PDT So as you all can see in the screen shot below in my blog form when I click submit when creating a new blog the parameters get sent but never actually get inserted into the MySQL command. Which you can see the post in the background is empty except for the Timestamp. Now with that being said this same form is used for my Edit Blog page. My form is a partial rendered in the new blog page and the edit blog page. So if I go edit that same blog page that was created with no input up submit of the edit's the parameters actually go through and then the blog post will show will all the information from your edits. class PostsController < ApplicationController before_action :find_post, only: [:edit, :update, :show, :delete] # Index action to render all posts def index @posts = Post.all end # New action for creating post def new @post = Post.new end # Create action saves the post into database def create @post = Post.new if @post.save(post_params) flash[:notice] = "Successfully created post!" redirect_to post_path(@post) else flash[:alert] = "Error creating new post!" render :new end end # Edit action retrives the post and renders the edit page def edit end # Update action updates the post with the new information def update if @post.update_attributes(post_params) flash[:notice] = "Successfully updated post!" redirect_to post_path(@post) else flash[:alert] = "Error updating post!" render :edit end end # The show action renders the individual post after retrieving the the id def show end # The destroy action removes the post permanently from the database def destroy if @post.destroy flash[:notice] = "Successfully deleted post!" redirect_to posts_path else flash[:alert] = "Error updating post!" end end private def post_params params.require(:post).permit(:strain, :straintype, :style, :light, :temp, :breeder, :private, :notes, :nutrients) end def find_post @post = Post.find(params[:id]) end end I just don't understand why the edit saves correctly but no the initial submit. |
Rails / Active Record 5.0.0 set id manually before create Posted: 24 Aug 2016 07:08 AM PDT I'm connecting a Rails application to another database and can't change the schema. This other database has a NOT NULL constraint on the id field for all of its tables (using uuid for id's). I'm trying to assign an id manually in a before_create but it seems the attribute is protected. Any way around this? Rails 5.0.0 |
Passenger not running my rails app on apache Posted: 24 Aug 2016 07:06 AM PDT My Passengerfile.json { "port": "80", "environment": "production", "address": "<ip>" } When I do this: passenger start I get these errors: *** ERROR: the Nginx configuration that Phusion Passenger Standalone generated internally contains problems. The error message returned by the Nginx engine is: nginx: the configuration file nginx.conf syntax is ok nginx: [emerg] bind() to <IP>:80 failed (99: Cannot assign requested address) nginx: configuration file nginx.conf test failed This probably means that you have found a bug in Phusion Passenger Standalone. Please report this bug to our Github issue tracker: https://github.com/phusion/passenger/issues In the bug report, please include this error message, as well as the contents of the file /tmp/passenger-standalone-1fs1r7z.log ########################################################################## # Passenger Standalone is built on the same technology that powers # Passenger for Nginx, so any configuration option supported by Passenger # for Nginx can be applied to Passenger Standalone as well. You can do # this by direct editing the Nginx configuration template that is used by # Passenger Standalone. # # This file is the original template. DO NOT EDIT THIS FILE DIRECTLY. # Instead, make a copy of this file and pass the `--nginx-config-template` # parameter to Passenger Standalone. # # Learn more about using the Nginx configuration template at: # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template # # *** NOTE *** # If you customize the template file, make sure you keep an eye on the # original template file and merge any changes. New Phusion Passenger # features may require changes to the template file. ############################################################## master_process on; daemon on; error_log '/home/deploy/env/railsapp/log/passenger.80.log' ; pid '/home/deploy/env/railsapp/passenger.80.pid'; worker_processes 1; events { worker_connections 4096; } http { log_format debug '[$time_local] $msec "$request" $status conn=$connection sent=$bytes_sent body_sent=$body_bytes_sent'; include '/usr/share/passenger/mime.types'; passenger_root '/usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini'; passenger_abort_on_startup_error on; passenger_ctl cleanup_pidfiles L3RtcC9wYXNzZWtc3RhbmRhbG9uZS51Y2hlci5waWQ=; passenger_ctl integration_mode standalone; passenger_ctl standalone_engine nginx; passenger_user_switching off; passenger_ruby /home/deploy/.rbenv/versions/2.3.1/bin/ruby; passenger_user deploy; passenger_default_user deploy; passenger_analytics_log_user deploy; passenger_log_level 3; ### BEGIN your own configuration options ### # This is a good place to put your own config # options. Note that your options must not # conflict with the ones Passenger already sets. # Learn more at: # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template ### END your own configuration options ### default_type application/octet-stream; types_hash_max_size 2048; server_names_hash_bucket_size 64; client_max_body_size 1024m; access_log off; keepalive_timeout 60; underscores_in_headers on; gzip on; gzip_comp_level 3; gzip_min_length 150; gzip_proxied any; gzip_types text/plain text/css text/json text/javascript application/javascript application/x-javascript application/json application/rss+xml application/vnd.ms-fontobject application/x-font-ttf application/xml font/opentype image/svg+xml text/xml; server { server_name _; listen <IP>:80; root '/home/deploy/env/railsapp/public'; passenger_app_root '/home/deploy/env/railsapp'; passenger_enabled on; passenger_app_env 'production'; passenger_spawn_method 'smart'; passenger_load_shell_envvars off; # Rails asset pipeline support. location ~ "^/assets/.+-([0-9a-f]{32}|[0-9a-f]{64})\..+" { error_page 490 = @static_asset; error_page 491 = @dynamic_request; recursive_error_pages on; if (-f $request_filename) { return 490; } if (!-f $request_filename) { return 491; } } location @static_asset { gzip_static on; expires max; add_header Cache-Control public; add_header ETag ""; } location @dynamic_request { passenger_enabled on; } ### BEGIN your own configuration options ### # This is a good place to put your own config # options. Note that your options must not # conflict with the ones Passenger already sets. # Learn more at: # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template ### END your own configuration options ### } passenger_pre_start http://<IP>/; } I have already followed the full tutorial at passenger website. I have installed everything. When I visit my then I am able to see the app directory like an FTP server. It is not executing the ruby code. So this proves apache is working fine. I have already added this line to my apache configuration: PassengerRuby /home/deploy/.rbenv/versions/2.3.1/bin/ruby |
Is there any callback need to setstate in pubnub? Posted: 24 Aug 2016 06:39 AM PDT I have set setstate in pubnub with data and uuid but when request coming from mobile end at my web end then getting error Pubnub::Event: Error while calling callback #<NoMethodError: undefined method '[]' for nil:NilClass> |
Unit testing to protect against production Posted: 24 Aug 2016 06:34 AM PDT We recently had a bug go into production where we added validates_presence_of to a model, but that column was nil for any records created before the change, so any code that instantiated the model on old data was broken. This seems to be in a class of bugs that can only be caught when tested against the production data. Is there a way to create unit tests that protect against these types of issues? |
Redirect with status: 401 hangs on "You are being redirected." How do I force redirect? Posted: 24 Aug 2016 06:47 AM PDT I am seeing the following page on unauthorized 401 redirection using rails 4: I am fine with this page rendering, but not OK with the page hanging. The link with anchor text 'redirected' works fine in redirecting to the correct page, but it must be clicked. In other words, the message is incorrect, and I am not being actively redirected. How do I force redirect? Here is the code that enables this, in action_controller/metal def redirect_to(options = {}, response_status = {}) #:doc: raise ActionControllerError.new("Cannot redirect to nil!") unless options raise AbstractController::DoubleRenderError if response_body self.status = _extract_redirect_to_status(options, response_status) self.location = _compute_redirect_to_location(request, options) self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(location)}\">redirected</a>.</body></html>" end |
Rspec test in rails error Posted: 24 Aug 2016 06:24 AM PDT I am newbie in rspec test. I have a file /spec/models/class_spec.rb. The content of the file is require 'rails_helper' RSpec.describe Class, :type => :model do #pending "add some examples to (or delete) #{__FILE__}" before(:each) do @my_class=Factory.create(:class, params) end end I also have a /spec/rails_helper file. When I run rspec in command line command : rspec spec/models/class_spec.rb I gets the following error /usr/local/rvm/gems/ruby-2.3.1/gems/airbrake-ruby-1.4.4/lib/airbrake-ruby.rb:102:in `configure': the 'default' notifier was already configured (Airbrake::Error) from /home/akhil/test-soko/ver3/sokonokado/config/initializers/errbit.rb:1:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `load' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `block in load' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:240:in `load_dependency' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `load' Can someone tell me about issue and also give a link to a tutorial for learning to write test codes using rspec. Thanks in advance My gem list is gem "rails-erd" gem 'letter_opener' gem 'spring' gem 'faker' gem 'pry-rails' gem 'pry-byebug' gem 'rspec-rails' gem 'factory_girl_rails' |
Best practice for rails multiple joins; conditional results from associated tables and parent table? Posted: 24 Aug 2016 06:15 AM PDT Im building a simple search engine to select multiple values form multiple associated tables. Relations are: Employee::Profile Employee::Profile::Branches From the base Profile im getting the state_id, career_id From the associated models there is a *_id column like branch_id. My goal is to search for some values from the table Employee::Profile And then proceed with the associated models. Also the associated models should be queried conditional. A form is posting the params to the controller action which looks like: @employees = Employee.joins(:employee_profile).where(Employee::Profile.table_name => {completed: true }).limit(50) @employees = Employee.joins(:employee_profile) .where(Employee::Profile.table_name => {completed: true }) .where(Employee::Profile.table_name => {state_id: params[:state]}) if params[:state] @employees = @employees.joins(:employee_profile) .where(Employee::Profile.table_name => {career_id: params[:career]}) if params[:career] What would be the most efficient way to conditional build this query up and adding the values of each conditional query to @employers ( e.g. states + careers ) The params that are provided to the controller ( career or state ) should all be added together to a final @employees. I am reading up on the joins in AR but not sure on how to best approach this, also in regards to performance. BTW: the params like state_id are arrays and consists of id's [1,2,3] I have added indexes the postgres database for them. |
NoMethodError in PostsController#upvote undefined method `upvote_by' for nil:NilClass Posted: 24 Aug 2016 06:09 AM PDT screenshot Currently I'm using acts_as_votable gem along with bootstrp-sass gem,I want to upvote the post when glyphicon icon is clicked, instead it throws me above errors. This is my posts_controller.rb file class PostsController < ApplicationController before_action :authenticate_user!, except: [:index, :show] def search if params[:search].present? @posts = Post.search(params[:search]) else @posts = Post.all end end def index @posts = Post.all.order('created_at DESC') end def new @post = Post.new end def create @post = Post.new(post_params) if @post.save redirect_to @post else render 'new' end end def show @post = Post.find(params[:id]) end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if @post.update(params[:post].permit(:title, :date, :time, :location)) redirect_to @post else render 'edit' end end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to root_path end def upvote @post.upvote_by current_user redirect_to :back end private def post_params params.require(:post).permit(:title, :date, :time, :location) end end This is my show.html.erb file <div id="post_content"> <h1 class="title"> <%= @post.title %> </h1> <p class="date"> Submitted <%= time_ago_in_words(@post.created_at) %> Ago <% if user_signed_in? %> | <%= link_to 'Edit', edit_post_path(@post) %> | <%= link_to 'Delete', post_path(@post), method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> </p> <p class="date"> <%= @post.date %> </p> <p class="time"> <%= @post.time %> </p> <p class="location"> <%= @post.location %> </p> <div id="comments"> <div class="btn-group pull-left"> <%= link_to like_post_path(@post), method: :put, class: "btn btn-default" do %> <span class="glyphicon glyphicon-heart"></span> <%= @post.get_upvotes.size %> <% end %> </div> <h2><%= @post.comments.count %> Comments</h2> <%= render @post.comments %> <h3>Add a comment:</h3> <%= render "comments/form" %> </div> This is my routes.rb file Rails.application.routes.draw do mount RailsAdmin::Engine => '/admin', as: 'rails_admin' devise_for :users resources :posts do resources :comments collection do get 'search' end member do put "like", to: "posts#upvote" end end root "posts#index" get '/about', to: 'pages#about' end And this is my post model class Post < ActiveRecord::Base acts_as_votable searchkick has_many :comments, dependent: :destroy validates :title, presence: true, length: {minimum: 5} validates :date, :time, :location, presence: true belongs_to :user end |
request ajax is not changing a page Posted: 24 Aug 2016 08:07 AM PDT I do have a problem. Turbolinks are off here I create a post $ -> createBooks = (res)-> result = JST["templates/create_book"] title: res.book.title author: res.book.author description: res.book.description id: res.book.id result $('.new_book').bind 'ajax:success', (e, data, status, xhr) -> res = $.parseJSON(xhr.responseText) result = createBooks(res) $('.drafts').append(result) everything works ok. I get a link like this on my page <a class="unpublish" data-method="post" rel="nofollow" data-remote="true" data-id="#{@id}" href="/books/14/unpublish" >Draft</a> here is my skim template <hr> <p>#{@title}</p> <p>#{@author}</p> <p>#{@description}</p> <div class="publishing" id="book_#{@id}"" <a class="publish" href="/books/#{@id}/publish" data-method="post" rel="nofollow" data-remote="true" data-id="#{@id}">Publish</a> </div> But then when I try to click on this link nothing visible happens on the page, but xhr is sent with a propper status, no errors. Its a mystery for me. Her is my listener $('.publish').bind 'ajax:success', (e, data, status, xhr) -> e.preventDefault() res = $.parseJSON(xhr.responseText) result = publishBooks(res) alert(result) book_id = "#book_" + $(this).data('id') $(book_id).html(result) I dersperatly need some help. Any help. When I reload the page everything again works ok Thaks to monsieur VKatz I finally have a working ecsample!!! look like this ready = -> createBooks = (res)-> result = JST["templates/create_book"] title: res.book.title author: res.book.author description: res.book.description id: res.book.id result publishBooks = (res)-> result = JST["templates/publish"] time: res.book.published_at id: res.book.id result unpublishBooks = (res)-> result = JST["templates/unpublish"] id: res.book.id result $('.new_book').bind 'ajax:success', (e, data, status, xhr) -> res = $.parseJSON(xhr.responseText) result = createBooks(res) $('.drafts').append(result) $('.publish').bind 'ajax:success', (e, data, status, xhr) -> res = $.parseJSON(xhr.responseText) result = publishBooks(res) book_id = "#book_" + $(this).data('id') $(book_id).html(result) $('.unpublish').bind 'ajax:success', (e, data, status, xhr) -> e.preventDefault() alert('okko okko') $(document).ready(ready) $(document).on('page:load', ready) $(document).on('page:update', ready) $(document).on('click', '.unpublish', ready); now its working but only for class unpublished? should I set this stuff for every class like "published" etc ??? |
Get background video to change to photo when device is changed on heroku Posted: 24 Aug 2016 05:49 AM PDT I am trying to change a background video to a background image when the device is changed from a desktop sized browser to a mobile sized browser . It works locally when I resize the browser, but it doesn't work when I push to heroku . Css @media (max-width: 768px) { .only_small { background-image:url('Goldengate.png'); min-height: 100vh; min-width: 100vw; background-position: center; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } } Html <div class = "only_small"> <div class ="vid_class"> <iframe src="https://player.vimeo.com/video/125312911?autoplay=1&loop=1" width="1600" height="900" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </div> |
rails save how many times a page has been viewed Posted: 24 Aug 2016 06:33 AM PDT So i'm wanting to save a number of how many times an event has been viewed. Basically this is to assist me order the popularity of the events. So i would do it on when the db row is selected but my searchkick is selecting the rows to show back. So i don't think i have any other choice but to put it in the show method? Heres whats in my show method (thats important) def show @event = Event.find(params[:id]) end what would be the best way to have it count when the view is shown? Ideally it would be amazing if i could also have it so it was unique to ip address (so someone can't spam the url) Sam |
how can I override the devise controller Posted: 24 Aug 2016 06:01 AM PDT I am trying to override the devise controller but my changes don't have any affects. this is my sessions_controller.rb for example class Users::SessionsController < Devise::SessionsController # before_action :configure_sign_in_params, only: [:create] # GET /resource/sign_in def new super authorize! :new, @user end # POST /resource/sign_in def create super authorize! :create, @user end # DELETE /resource/sign_out # def destroy # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_in_params # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) # end end this should take the def new of the 'normal' sessions controller and add the 2nd line to it. the link of the original session_controller on github and this is my routes.rb Rails.application.routes.draw do resources :sessions resources :corsin_lists resources :fileuploads do collection { post :import } end root 'documents#index' resources :documents resources :entries resources :documents do member do get :entries end end devise_for :users, :controllers => {:sessions => "users_sessions"} end |
How to debug and speed up slow has_one association load? Posted: 24 Aug 2016 05:12 AM PDT TL;DR @payment.order # takes from 3 to 15 seconds, unacceptable There are 1757k Orders and 640k Payments in a Postgres database. How to debug why it takes so long to load the association, and how to make it faster? If database indexing is the issue, how to verify whether it is the case or not; how to rebuild an index? Discussion I have these two legacy models: class Payment < ActiveRecord::Base has_one :order end class Order < ActiveRecord::Base # SCHEMA # t.references :payment, index: true belongs_to :payment end I know that it would be more correct if Payments belonged to Orders, but that's how the app is and can not be changed. The history is long and convoluted, the payment_id on orders table has been dropped, restored and add_index -ed, values changed in batch tasks. After one payment_id field drop and restore I noticed that calling a simple association load in console takes very long @payment.order Since accessing this association is crucial to app performance, I overwrote the vanilla Rails association class Payment < ActiveRecord::Base # has_one :order # too slow! def order return nil if self.new_record? return @order ||= Order.where(payment_id: self.id).limit(1).last # takes just 0.3s end Now the load is even faster than it was before, but, naturally, the getter method does not behave like a true association, specifically, I can not use Payment.joins(:order) How do I restore the association and have it performant? |
Rails : serialize Ruby range Posted: 24 Aug 2016 05:30 AM PDT I'm running Rails 3.2.17 (also tried it with 3.2.22). I have trouble with serialization of a ruby Range in my model: class MyModel < ActiveRecord::Base attr_accessible :my_column serialize :my_column, Range end When I try to create an record like this: MyModel.create() # Or like this MyModel.create({my_column: (0..2)}) I have this error: ArgumentError: wrong number of arguments (0 for 2..3) How can I solve this? EDIT I have found a way like this: class MyModel < ActiveRecord::Base attr_accessible :my_column # NO MORE SERIALIZE def my_column=(val) self[:my_column] = YAML.dump(val) end def my_column YAML.load(super || YAML.dump(nil)) end end |
Adding integer array column with rails migration error Posted: 24 Aug 2016 06:58 AM PDT I want to add migration that will do the same as: ALTER TABLE my_table ADD COLUMN int_array integer[]; with result column: int_array, type: integer[], storage: extendent I tried these options, but it doesn't work. def change add_column :my_table, :int_array, :integer, array: true, default: [] #first option add_column :my_table, :int_array, :integer, array: true, default: '{}' #second options end Errors that occurred: == AddIntArrayToMyTable: migrating ========================================== -- add_column(:my_table, :int_array, :integer, {:array=>true, :default=>[]}) rake aborted! StandardError: An error has occurred, this and all later migrations canceled: PG::InvalidTextRepresentation: ERROR: incorrect syntax for input integer: "--- [] " : ALTER TABLE "my_table" ADD COLUMN "int_array" integer DEFAULT '--- [] and == AddIntArrayToMyTable: migrating ========================================== -- add_column(:my_table, :int_array, :integer, {:array=>true, :default=>"{}"}) rake aborted! StandardError: An error has occurred, this and all later migrations canceled: PG::InvalidTextRepresentation: ERROR: incorrect syntax for input integer: "{}" Any ideas what could be wrong? I'm using rails Rails 3.2.16 and postgreSQL 9.4 Thanks in advence. |
Ruby on Rails - Silence Logger Error Posted: 24 Aug 2016 04:52 AM PDT Since I updated my Rails 3 to 4 i get CookieOverflow Errors, so now i try to make a session store at database with the gem "activerecord_session_store". My session_store.rb : Fos5::Application.config.session_store :active_record_store But now I get this Error : undefined method `silence_logger' for #Log4r::Logger:0x501c828> I know I should include this Silence Logger: MyLogger.send :include, ActiveRecord::SessionStore::Extension::LoggerSilencer My logger.rb : require 'log4r' outputter = Log4r::FileOutputter.new('log4r', :filename => "foobar.log") outputter.formatter = Log4r::PatternFormatter.new( :date_pattern => "%FT%T.000Z", :pattern => "%d [%l] %m" ) logger = Log4r::Logger.new('log4r') logger.outputters = [outputter] If i try to add this Code there i get a Error, so where should I add this Code ? |
Rails SQL query counts results when not asked [duplicate] Posted: 24 Aug 2016 07:29 AM PDT This question is an exact duplicate of: This rails/sql code... @new_relationships = User.select('*') .from("(#{@rels_unordered.to_sql}) AS rels_unordered") .joins(" INNER JOIN relationships ON rels_unordered.id = relationships.character_id ORDER BY relationships.created_at DESC ") produces a query that begins like this: SELECT COUNT(*) FROM (SELECT ..... Why is it counting the records?? I haven't asked for a count. I simply want to select all columns after the join: SELECT * FROM (SELECT ..... |
Rails version migration Posted: 24 Aug 2016 04:43 AM PDT I'm trying to upgrade my rails app from Rails 3 to Rails 4.2 . Seems like many changes have been incorporated and due to which i'm getting following error:- Uncaught exception: undefined method `create' for class `ActiveRecord::Base' Unable to figure out a fix for it. Any help would be highly appreciated. |
Teardown called in the middle of a test Capybara Posted: 24 Aug 2016 07:25 AM PDT I have been trying to create the following test : Edit a model (client side), check if the view is updated and if the model changed in database. there is the code : test 'a' do user = User.joins(:organization_users).find_by organization_users: { role: OrganizationUser.roles.values_at(:ORGANIZER, :ADMINISTRATOR) } sign_in_user user criterion = create(:criterion, scoring_id: @scoring.id, name: "Test criterion name", description: "Test description") step = create(:step, criterion_id: criterion.id) visit "scorings/" + (@scoring.id).to_s + "/criteria" find("#criteria > div > div > a > i").click() fill_in 'name', with: 'New name' fill_in 'description', with: 'New description' find('#criterion-modal > div:nth-child(2) > form > div:nth-child(4) > input').click() criterion = criterion.reload assert criterion.name == 'New name' end ` As you can see at the end of the test i reload the criterion, but when i do that the teardown function is called. After that the Database is cleaned and i get the error "cant find criterion id:1". I'm only using minitest , factory girl and Capybara. So what i want to understand is why Teardown is called since its not the end of the test and how can i fix that ? Thank you. |
Unexpected simple-form label translation Posted: 24 Aug 2016 07:23 AM PDT I have an unusual problem whereby simple_form labels are being translated for one user on one browser when I update the "preferred language" of a completely different user on another browser. This also only happens in production mode. Also, it is worth saying that refreshing the page for the user who was unintentionally affected may or may not display the expected English label. In our app, if I update the "preferred language" of the current user, the labels will not be translated which is expected. One users labels are only affected by a user on another browser who updates their "preferred language". In my simple_form.rb, you can that translations of labels is actually turned off right now: # When false, do not use translations for labels. # config.translate_labels = true So, they shouldn't be translated at all nevermind in this scenario. We use redis in our app and I temporarily disabled the redis cache to check that caching was not the problem(config.cache_store = :null_store ). The change proved that redis was not the issue as the same thing kept happening. I really don't know where to start with what code to include so if people have suggestions that would be great. Online, my searches have included things like the following: - redis i18n caching rails
- simple_form localization cache
Alternatively, can anyone explain why simple form button labels are being translated when my simple form configuration contains?: # When false, do not use translations for labels. # config.translate_labels = true Is the default true? |
Ruby on rails: Missing access token when trying to upload file to google drive using paperclip Posted: 24 Aug 2016 04:24 AM PDT I use paperclip-googledrive gem to upload file on my drive account, so i have created a project on google APIs and i have followed instructions cited on https://github.com/shoaibmalik786/paperclip-googledrive-new, I have runing rake google_drive:authorize and i entred the required informations and i have got an access token my config/google_drive.yml: client_id: <%= ENV["CLIENT_ID"] %> client_secret: <%= ENV["CLIENT_SECRET"] %> access_token: <%= ENV["ACCESS_TOKEN"] %> refresh_token: <%= ENV["REFRESH_TOKEN"] %> So when i click on upload file button, it show error says: Missing access token , i have copied access token code from the console and paste it to config/google_drive.yml in the third line in place of <%= ENV["ACCESS_TOKEN"] %> , that's work well and the file was uploaded successfuly, but after 1 hour i have tried the operation but it was failed, and i think that the access token haven't been refreshed, so what to do to refresh it automaticly ? |
You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site.
ReplyDeletepg online
Whether you are involved in affiliate marketing, selling items through ClickBank, or promoting your own personal business and website, ads are an important part of one's success. Some people make a recurring income simply by placing advertisements on the websites that get a lot of traffic.
ReplyDeletehttps://www.ufa365.info/
You have raised an important issue..Thanks for sharing..I would like to read more current affairs from this blog..keep posting..
ReplyDeleteแทงบอลเต็ง
So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site.
ReplyDeleteแทงบอลสเต็ป
Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first”.
ReplyDeleteรีวิวเว็บพนัน
mmm.. good to be here in your article or post, whatever, I think I should also work hard for my own website like I see some good and updated working in your site.
ReplyDeleteรีวิวเว็บพนัน
I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work.
ReplyDeleteแทงบอลสเต็ป
Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
ReplyDeleteเว็บแทงบอลฝากถอนauto
I read this article. I think You put a lot of effort to create this article. I appreciate your work. เว็บแทงบอลสเต็ปไม่มีขั้นต่ำ
ReplyDeleteConsequently, starting in the amount of electronic marketing strategy, is whenever a company's existing website, which will be to review the present site and its purpose is to improve the potency of the future. There is no evidence that the development and implementation of a method to be significantly different way of electronic marketing. Strategic planning for enterprise development or strategic marketing to comply with the established framework should still be
ReplyDeleteเว็บแทงบอลออโต้
เว็บแทงบอลออโต้
ReplyDeleteYou made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this.
ReplyDeleteทำไมต้องเล่นบาคาร่า
I am often to blogging and that i actually appreciate your posts. This article has truly peaks my interest. I am going to bookmark your internet site and keep checking for first time data
ReplyDeleteสล็อตบนมือถือ
Should there be another persuasive post you can share next time, I’ll be surely waiting for it.
ReplyDeleteแทงบาสเว็บไหนดี
You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. ThanYou made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this.
ReplyDeleteks for sharing the such information with us to read this.บาคาร่าsa-gaming
his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
ReplyDeleteแทงบาสออนไลน์
Yes, great US Military force. Also, in his post you have given a chance to listen about US Military. I really appreciate your work. Thanks for sharing it.
ReplyDeleteสล็อตออนไลน์