Dynamic Data with Google Tag Manager and TurboLinks Posted: 03 Jan 2017 08:00 AM PST How can I set up GTM with TurboLinks? The problem: GTM and the SEO team asks me to add this to my Head: <% if user_signed_in? %> dataLayer = [{'userID': '<%= current_user.id %>'},{'userCategory': 'User'}]; <% end %> </script> <!-- Paste this code as high in the <head> of the page as possible: --> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-N7MDCP');</script> <!-- End Google Tag Manager --> This will be cached by TurboLinks. I could try to wrap this in page:change, but that won't update the values for user_signed_in etc. Can I safely move this into the body, where TurboLinks will refresh it? If not, how else can i get GTM to work with a dynmic datalayer and GTM? |
Optional where in Rails Posted: 03 Jan 2017 07:53 AM PST How can I make a where optional in Rails? I tried: @pages = Page .where(status: params[:status].present? ? params[:status] : 1) .where(parent_id: nil) if params[:status].blank? .order(sort_column + ' ' + sort_direction) But it looks to exit the block and instead returns: undefined method 'where' for true:TrueClass . |
Disable Submit button until Input fields filled in RAILS Posted: 03 Jan 2017 07:31 AM PST I want to disable the submit button until my input fields have been filled in. I am new to rails and not so much with JS and Coffee, I have been trying to run this feature but it is not getting to work. I have come up with this validate = -> if $('#description').val().length > 0 and $('#image').val().length > 0 and $('#url-input').val().length > 0 $('input[type=submit]').prop 'disabled', false else $('input[type=submit]').prop 'disabled', true return $(document).ready -> validate() $('#description, #image, #url-input').change validate return` Html.haml = simple_form_for @post, html: { multipart: true } do |f| - if @post.errors.any? #errors %h2 = pluralize(@post.errors.count, "error") prevented this Post from saving %ul - @post.errors.full_messages.each do |msg| %li= msg .form-group = f.input :title,:label => "Project Name", input_html: { class: 'form-control' } .form-group %label{:for => "Image"} image %input#image.form-control-file{"aria-describedby" => "fileHelp", :type => "file"}/ .form-group %label{:for => "url-input"} Project Link %input#url-input.form-control{:type => "url", :value => "https://"}/ .form-group %label{:for => "description"} Description %textarea#description.form-control{:rows => "3"} %small#descriptionHelp.form-text.text-muted Clear it up please %button#add.btn.btn-info{:type => "submit", :disabled => "disabled" } submit Any help out would be appreciate it! |
Nginx + Unicorn : difference between both worker_processes Posted: 03 Jan 2017 07:28 AM PST I have a rails app running on a Nginx + Unicorn environnement I see that both have a "worker_processes" in their config file and I wonder what is the optimal configuration If I have 4 cores, should I put 4 for both? Or 1 for nginx and 4 for unicorn? (by the way, I am using sidekiq too, so what about sidekiq concurrency?) |
api resource rails routes Posted: 03 Jan 2017 07:20 AM PST So I have some API resources in my app, and some regular resources, and for regular resources I use : resources :books And then I could pass except: %i(destroy new edit) or only so works great! However for my resource I ll never have new/edit actions, sometimes I will need to pass except and only options too. I was thinking to create something like: api_resources :books Which comes without new/edit actions by default, how would I do that? |
Can't hit API endpoint in Rails using Mongodb Posted: 03 Jan 2017 07:40 AM PST I am attempting to build a Rails backend using Mongodb that is just an API application. I have an events model and api controller and when I go to localhost:3000/events/2, I am getting a 404 error, although I know the record is in my database: { "_id" : 2, "name" : "String Cheese", "location" : "Durham, NC", "price" : "40.00" } My controller looks like this: class API::V1::EventsController < ApplicationController respond_to :json def show respond_with Event.find('_id') end private def event_params params.require(:event).permit(:name, :url, :location, :dates, :price, :info, :genre, :address, :city, :tags) end end And my routes look like this: require 'api_constraints' Rails.application.routes.draw do namespace :api, defaults: { format: :json }, path: '/' do scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do resources :users, only: [:show] resources :events, only: [:show] end end end And then I have an api_constraints.rb in my lib folder that looks like this: class ApiConstraints def initialize(options) @version = options[:version] @default = options[:default] end def matches?(req) @default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}") end end This is to remove the need for having the api version number in the uri. I'm not sure if it is effecting my endpoint. So then when I start my server and go to localhost:3000/events/2 I get a 404 error: {"status":404,"error":"Not Found","exception":"#\u003cMongoid::Errors::DocumentNotFound: \nmessage:\n Document(s) not found for class Event with id(s) {\"_id\"=\u003e\"2\"}.\nsummary:\n When calling Event.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): {\"_id\"=\u003e\"2\"} The stack trace is actually even longer, so i can post the whole thing if anyone needs it. Any help would be greatly appreciated. |
How can I construct a rule engine using Ruby on Rails? Posted: 03 Jan 2017 07:24 AM PST I'm supposed to create a simple rule engine in ruby. Any leads on how I can proceed? I have found the following gems which does the same - Ruleby
- Wongi
But it seems like there should be a better way to implement a rule engine. Any thoughts on how to proceed would be helpful. |
How do I get rid of brackets that are appearing around my Rails model error message? Posted: 03 Jan 2017 07:10 AM PST I'm using Rails 5. In my model, I set an error if one of my fields isn't valid ... errors.add(:my_field, 'The field is not in the correct format') and then in my view, I display the error like so ... <% if !@user.errors[:my_field].empty? %><span class="profileError"> <%= @user.errors[:my_field] %></span><% end %> When the error is displayed, it appears as ["The field is not in the correct format"] How do I get rid of those brackets that appear around the error? This seems like a really simple problem but I don't know how those things are creeping in there. |
Syntax error on empty line Posted: 03 Jan 2017 06:56 AM PST I have the following error showing, not sure what went wrong... /home/ubuntu/section3/alpha-blog/app/views/users/_form.html.erb:39: syntax error, unexpected keyword_end, expecting ')' '.freeze; end ^ /home/ubuntu/section3/alpha-blog/app/views/users/_form.html.erb:46: syntax error, unexpected keyword_ensure, expecting ')' /home/ubuntu/section3/alpha-blog/app/views/users/_form.html.erb:48: syntax error, unexpected keyword_end, expecting ')' My codes are below. Line39 is <% end %> and line 46 & 48 are empty. <%= render 'shared/errors', obj: @user%> <div class= 'row'> <div class = 'col-xs-12'> <%= form_for(@user, :html => {class: "form-horizontal", role: "form"}) do |f| %> <div class="form-group"> <div class= "control-label col-sm-2"> <%= f.label :username %> </div> <div class="col-sm-8"> <%= f.text_field :username, class: "form-control", placeholder: "enter username", autofocus: true %> </div> </div> <div class= "form-group"> <div class="control-label col-sm-2"> <%= f.label :email %> </div> <div class = "col-sm-8"> <%= f.email_field :email, class: "form-control", placeholder: "Enter email" %> </div> </div> <div class = "form-group"> <div class= "control-label col-sm-2"> <%= f.label :password %> </div> <div class = "col-sm-8"> <%= f.password_field :password, class: "form-control", placeholder: "Enter password" %> </div> </div> <div class= "form-group" > <div class = "col-sm-offset-2 col-sm-10"> <%= f.submit(@user.new_record? ? "Sign up": "Update account", class: 'btn btn-primary btn-lg' %> </div> </div> <% end %> <div class = "col-xs-4 col-xs-offset-4"> [<%= link_to "Cancel request and return to articles listing", articles_path %> ] </div> </div> </div> |
Thinking sphinx without condition on array of id is not working Posted: 03 Jan 2017 06:48 AM PST I am using ruby 1.9.3p392 rails 3.2.21 thinking sphinx 3.1.0 and Sphinx 2.2.4-id64-release user_index.rb file is :- ThinkingSphinx::Index.define :user, :with => :active_record do indexes first_name, :sortable => true indexes last_name indexes email indexes user_name indexes company_id indexes id indexes user_type_id indexes department.name indexes department.id, :as => :department_id end When i search as:- assigned_user_ids = [372, 373, 374, 375, 367, 376, 377, 378, 379, 380] @users = User.search(Riddle::Query.escape(params[:search]), :conditions => {:company_id => @company.id}, :without => {:id => assigned_user_ids}, :per_page => PAGINATION_SIZE, :page => params[:page]) But it is still showing the user with id = 372 |
Wanted some idea to manage pending_approval and in_progress webpages in Ruby on Rails 4 Posted: 03 Jan 2017 06:40 AM PST I have written a CMS in Ruby on Rails 4 and I have managed the webpages from the admin part. Webpages -> Anyone can create a webpage from admin after login and each page has four status "in_progress", "pending_approval", "published" and "archived", For now I have implemented the functionality for one status i.e "published" if any webpage that has status "published" then it will be show to the user otherwise it will through 404 error. Now I have to implement the rest of the status for the webpages created by admin user, As per my requirement pending_approval , in_progress -> I have to randomize the url and save the page inside any tmp directory and it will be visible to review team and once it's status will change to "publish" then move to its main folder (view/pages/file_path). |
Access an attribute from other model Posted: 03 Jan 2017 06:50 AM PST This is a part of my model (Partner) before_validation(on: :create) do self.name = name.upcase self.institution = institution.upcase self.position = position.upcase self.street = street.upcase self.neighborhood = neighborhood.upcase self.city = city.upcase self.state = state.upcase self.email = email.upcase self.birth_city = birth_city.upcase self.spouse = spouse.upcase end street and neighborhood are attributes from address model. By this way, i´m getting an error before saving it to db. How can I solve it? |
cant catck ajax response Posted: 03 Jan 2017 06:56 AM PST I do have a controller action def create @place = Place.new(place_params) respond_to do |format| if @place.save format.json { render json: @place, status: :created } end end and a form div.col-sm-6 h1 Place =form_for Place.new, remote: true do |f| div = f.label :address, class: 'label_hidden' = f.text_field :address, class: "form-control" div = f.label :title, class: 'label_hidden' = f.text_field :title, class: "form-control" div = f.label :longitude, class: 'label_hidden' = f.text_field :longitude, class: "form-control" div = f.label :latitude, class: 'label_hidden' = f.text_field :latitude, class: "form-control" div = f.submit 'Create', class: "btn btn-default" so I need to get an ajax response. I ve tryed somth like this $(document).ready -> $("#new_place").on("ajax:success", (e, data, status, xhr) -> console.log xhr.responseText ).on "ajax:error", (e, xhr, status, error) -> console.log "ERROR" But that does not work. Need some help on this |
Rails: List all the items from a table to drop-down list using Devise Posted: 03 Jan 2017 06:27 AM PST I'm new to Rails. I use devise for authentication in my Rails 5.0.1 project. # Here is my Helper Module module CategoriesHelper def categories_for_select Category.all.collect { |m| [m.name] } end end in _form.html.erb page <div class="field"> <%= f.label :category_name %> <%= f.select(:category_name, categories_for_select, :prompt => 'Select') %> <%= link_to 'Create New Category', new_category_path %> How can I list all the items from the Category table to a drop-down list that is associated with the current_user. UPDATE: Schema create_table "categories", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" end |
Failed to send email in rails(Staging environment) Posted: 03 Jan 2017 05:52 AM PST We have been using amazon-ses email service in our application to send mails. It was working fine before. Suddenly it stopped working. It does not show any errors. What could be the reason behind this ? |
Rspec error in registrations action of devise Posted: 03 Jan 2017 06:59 AM PST I implement point system. And when User creates , User has some points. My registrations_controller_spec.rb is below. require 'rails_helper' RSpec.describe Users::RegistrationsController, type: :controller do describe 'sign in' do before do @user=build(:user) @request.env["devise.mapping"] = Devise.mappings[:user] end it 'adds 60 point with default' do post :create , params: {name: @user.name , sex: @user.sex , age: @user.age ,country: @user.country ,email: @user.email ,password: @user.password, password_confirmation: @user.password , confirmed_at: DateTime.now } expect(response).to render_template root_path expect(@user.points).to eq (60) end end end and My registrations_controller.rb is below. class Users::RegistrationsController < Devise::RegistrationsController def create super if resource.save resource.rewards.create(point: 60) end end end and It is custom controller , so My config/routes.rb is below. Rails.application.routes.draw do devise_for :users, controllers: { registrations: 'users/registrations' , } end I have the error below. expected: 60 got: 0 In short , I think that I couldn't create user because I had the error below when I changed 'expect(@user.points).to eq (60)' to 'expect(@user.reload.points).to eq (60)'. Couldn't find User without an ID Why do I have the error? Please help me. Anyway, User model file is below. class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :timeoutable, :omniauthable, :omniauth_providers => [:facebook] default_scope -> {order(created_at: :desc)} validates :name , presence: true , length: {maximum: 18} validates :sex , presence: true validates :age , presence: true validates :country , presence: true def points(force_reload = false) self.rewards(force_reload).sum(:point) end end and My applicationcontroller is below (uses devise strong parameter in the file) class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :configure_permitted_parameters, if: :devise_controller? def after_sign_in_path_for(resource) if (session[:previous_url] == user_path(resource) ) user_path(resource) else session[:previous_url] || user_path(resource) end end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name,:age,:sex,:skill,:content, :picture , :country , :language1, :language2 ]) devise_parameter_sanitizer.permit(:account_update, keys: [:name,:age,:sex,:skill,:content, :picture , :country , :language1, :language2 ]) end end |
UnknownFormat with Devise and custom controllers Posted: 03 Jan 2017 06:29 AM PST I am using Rails 5 and Devise. Because I want custom layouts for login and recover password pages I had to run rails generate devise:controllers I also set my routes to: devise_for :users, controllers: { sessions: 'users/sessions', passwords: 'users/passwords' } Login works fine. Now, when I want my users to change their profile I set a link to edit_user_registration_path Which opens a form where they can set their email and password but when I submit the form I get the error: ActionController::UnknownFormat in Devise::RegistrationsController#update In the registrations controller everything is commented out because I do not want to use custom code here. Full trace: responders (2.3.0) lib/action_controller/respond_with.rb:207:in `respond_with' devise (4.2.0) app/controllers/devise/registrations_controller.rb:60:in `update' actionpack (5.0.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action' actionpack (5.0.0.1) lib/abstract_controller/base.rb:188:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/rendering.rb:30:in `process_action' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action' activesupport (5.0.0.1) lib/active_support/callbacks.rb:126:in `call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile' activesupport (5.0.0.1) lib/active_support/callbacks.rb:455:in `call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action' activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (5.0.0.1) lib/abstract_controller/base.rb:126:in `process' actionview (5.0.0.1) lib/action_view/rendering.rb:30:in `process' actionpack (5.0.0.1) lib/action_controller/metal.rb:190:in `dispatch' actionpack (5.0.0.1) lib/action_controller/metal.rb:262:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve' actionpack (5.0.0.1) lib/action_dispatch/routing/mapper.rb:16:in `block in <class:Constraints>' actionpack (5.0.0.1) lib/action_dispatch/routing/mapper.rb:46:in `serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call' warden (1.2.6) lib/warden/manager.rb:35:in `block in call' warden (1.2.6) lib/warden/manager.rb:34:in `catch' warden (1.2.6) lib/warden/manager.rb:34:in `call' rack (2.0.1) lib/rack/etag.rb:25:in `call' rack (2.0.1) lib/rack/conditional_get.rb:38:in `call' rack (2.0.1) lib/rack/head.rb:12:in `call' rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context' rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call' activerecord (5.0.0.1) lib/active_record/migration.rb:552:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call' railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call' rack (2.0.1) lib/rack/method_override.rb:22:in `call' rack (2.0.1) lib/rack/runtime.rb:22:in `call' activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call' rack (2.0.1) lib/rack/sendfile.rb:111:in `call' railties (5.0.0.1) lib/rails/engine.rb:522:in `call' rack (2.0.1) lib/rack/handler/webrick.rb:86:in `service' /usr/local/var/rbenv/versions/2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service' /usr/local/var/rbenv/versions/2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run' /usr/local/var/rbenv/versions/2.3.0/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread' |
both type of users in same model but had relation of many to many Posted: 03 Jan 2017 05:41 AM PST I need help for making association in models i had 2 model User -id -email -pass -usertype (company | doctor) company_doctor -id -user_id ( as a compnay id) -doctor_id (as a doctor id) can someone help out please |
Can't access data in ActiveHash Posted: 03 Jan 2017 05:56 AM PST I'm using the Gem active_hash https://github.com/zilkey/active_hash to create models for simple data that I don't want to create DB tables for. For example, I have this model setup for FieldTypes: class FieldType < ActiveHash::Base self.data = [ {:id => 1, :name => "text", :friendly_name => "Text"}, {:id => 2, :name => "textarea", :friendly_ => "Text Area"}, {:id => 3, :name => "image", :friendly_ => "Image"}, ] end And I'm trying to list these field types for a select: def field_types_for_select #FieldType.all.order('name asc').collect { |t| [t.friendly_name, t.name] } FieldType.pluck(:friendly_name, :name) end But I get an error that order, collect or pluck are not defined. How do I access this data? This works fine on other models, just not ActiveHash ones. According to the docs the model should work the same as ActiveRecord but I don't seem to be able to access it the same. FieldType.all works, but other methods do not. |
RoR error, issue with my Gemfile or test configuration Posted: 03 Jan 2017 05:27 AM PST I am fully aware that I asked a similar question before, but this time I have a lot more details about the situation. it seems like I cant test my application because there is something wrong with my Gemfile or test configuration. Apparently this is also known as an RoR error. I am using the cloud9 development environment, and my workspace is running ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]. the following is my Gemfile: source 'https://rubygems.org' gem 'devise' gem 'bootstrap-sass' #modernizr gem 'modernizr-rails' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.6' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end gem 'haml-rails' When I run rake test I get the following error: > [NOTE] > > You may have encountered a bug in the Ruby interpreter or extension libraries. > > Bug reports are welcome. > For details: http://www.ruby-lang.org/bugreport.html > > Aborted I got 3 controllers in my application and two of them are models. The 3rd controller is just a controller I made to handle the main views (the main interface) its not a model. I generated the 3rd model as a standalone controller but the other two controllers are part of scaffolds that I generated. (Client and Project) This is my clients controller test: require 'test_helper' class ClientsControllerTest < ActionController::TestCase setup do @client = clients(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:clients) end test "should get new" do get :new assert_response :success end test "should create client" do assert_difference('Client.count') do post :create, client: { name: @client.name, email: @client.email + "create" } end assert_redirected_to client_path(assigns(:client)) end test "should show client" do get :show, id: @client assert_response :success end test "should get edit" do get :edit, id: @client assert_response :success end test "should update client" do patch :update, id: @client, client: { name: @client.name } assert_redirected_to client_path(assigns(:client)) end test "should destroy client" do assert_difference('Client.count', -1) do delete :destroy, id: @client end assert_redirected_to clients_path end end project controller tests: require 'test_helper' class ProjectsControllerTest < ActionController::TestCase setup do @project = projects(:one) @client = clients(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:projects) end test "should get new" do get :new assert_response :success end test "should create project" do assert_difference('Project.count') do post :create, project: { client_id: @client, project_description: @project.project_description, project_timescale: @project.project_timescale, title: @project.title } end assert_redirected_to project_path(assigns(:project)) end test "should show project" do get :show, id: @project assert_response :success end test "should get edit" do get :edit, id: @project assert_response :success end test "should update project" do patch :update, id: @project, project: { client_id: @project.client_id, project_description: @project.project_description, project_timescale: @project.project_timescale } assert_redirected_to project_path(assigns(:project)) end test "should destroy project" do assert_difference('Project.count', -1) do delete :destroy, id: @project end assert_redirected_to projects_path end end Index controller test: require 'test_helper' class IndexControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success end test "should get contact" do get :contact assert_response:success assert_template layout: 'application' assert_select'title', 'My Notes' assert_select'h1', 'Contact Us' assert_select 'p', 'Complete the following form to get in touch with us.' end end client model test: require 'test_helper' class ClientTest < ActiveSupport::TestCase # test "the truth" do # assert true # end #tests to see if an empty client can be created test "no empty clients!" do client = Client.new client.save refute client.valid? end #checks if a valid client can be created test "should save valid clients" do client = Client.new client.name = "David" client.email = "example@gmail.com" client.save assert client.valid? end test "no duplicate emails" do client1 = Client.new client1.name = "David" client1.email = "example@gmail.com" client1.save assert client.valid? client2 = Client.new client2.name = "David" client2.email = "example@gmail.com" client2.save refute client.valid? end end project model test: require 'test_helper' class ProjectTest < ActiveSupport::TestCase # test "the truth" do # assert true # end setup do @client = clients(:one) end test "no empty projects" do project = Project.new project.save refute project.valid? end test "make valid projects" do project = Project.new project.title = "first project" project.project_description = "building a forum for a game clan" project.project_timescale = "1 month" project.save assert project.valid? end end clients.yml : # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: name: MyString email: MyText1 two: name: MyString email: MyText2 projects.yml: # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: client: one project_description: MyText project_timescale: MyString title: MyString two: client: two project_description: MyText project_timescale: MyString title: MyString |
Save Multiple Records Simultaneously with a single AJAX request? Posted: 03 Jan 2017 05:35 AM PST I'm using jQuery Sortable to drag cards between lists, like Trello. When the user is finished interacting with a card, I need to save all cards in that list. I'm currently doing it with an each loop, looping over all items of that type and saving each one with an AJAX request. ui.item.parent('.js-CardsContainer').children('.js-CardContainer').each(function() { var list_id = $(this).closest('.js-List').data('id'); var order = $(this).index(); var id = $(this).find('.js-Card').data('id'); console.log(order); $.ajax({ url: "/cards/" + id, type: "PATCH", data: { card: { list_id: list_id, order: order } }, success: function(resp) { // } }); }); It seems to work for lists with just a few cards. But when 5+ cards are being saved, some of them fail. I guess that's because separate AJAX requests are being used for each card? So, I think I need to combine all AJAX requests into a single request? I have no idea how to do that though. Can anyone help? This is going to my controller update action which looks like this def update @card = Card.find(params[:id]) if @card.update_attributes(shared_params) respond_to do |format| format.js {} format.json { render json: @card, status: :created, location: @card } end else render :edit end end |
Rails file upload: upload a folder Posted: 03 Jan 2017 06:31 AM PST I work on Rails project and client asked if I can add 'upload a folder' feature to simple file upload system that we have now. Currently it attaches files to model and then displays them on a page for download. Pretty basic. But I can't figure out how can I handle folder uploads, with every folder having it's own content. Is there any pre-made gems that can help accomplish that? We use Paperclip at the moment, but I don't mind migrating to Carrerwave or some other gem that would UPDATE I see that I was unclear about my needs. I need an upload system that could handle folders. Something like this. In Dropbox I am able to upload both files and folders. How can I make my uploaders accept folders and then display them alongside regular attached files? |
Prevent Maruku from posting so many log warnings Posted: 03 Jan 2017 05:08 AM PST I use Maruku in Rails simply to convert a Markdown file to HTML so I can use it with Nokogiri. (Maybe there's a better solution for that?) That works fine, but I get lots and lots of "Maruku tells you" messages in the log: ___________________________________________________________________________ | Maruku tells you: +--------------------------------------------------------------------------- | Could not find ref_id = "FIX" for md_link("FIX", nil) | Available refs are [] +--------------------------------------------------------------------------- That's really confusing and not needed here. Is there a way to silence Maruku so it only warns in the log if there's a real error? |
Rails and frindly_id. Couldn't find > Page with 'id' Posted: 03 Jan 2017 07:20 AM PST I use friendly_id gem in my app. Gem is simple to set up. Usually there are no problems with its setting. But now I have error: ActiveRecord::RecordNotFound in PagesController#show Couldn't find Page with 'id'=o-saite Pages model: class Page < ApplicationRecord extend FriendlyId friendly_id :slug_candidates, use: :slugged def slug_candidates [ :title, [:title, :id] ] end def normalize_friendly_id(title) title.to_s.to_slug.transliterate(:russian).normalize.to_s end end Pages controller: class PagesController < ApplicationController before_action :load_page, only: [:show] def show end private def load_page @page = Page.friendly.find(params[:id]) redirect_to action: action_name, id: @page.friendly_id, status: 301 unless @page.friendly_id == params[:id] end def page_params params.require(:page).permit( :title, :content, :slug ) end end SQL: mysql> select title, id, slug from pages; +------------------+----+----------+ | title | id | slug | +------------------+----+----------+ | О сайте | 1 | o-saite | | Доставка | 2 | dostavka | | Контакты | 3 | kontakty | | Ремонт | 4 | remont | +------------------+----+----------+ 4 rows in set (0.01 sec) When I worng? |
Is there any harm in breaking the cache from a different thread? Posted: 03 Jan 2017 05:35 AM PST Here's some pseudo code: out = Rails.cache.fetch("#{cache_key}/#{path}") do # if the content has never before been requested get_stuff_from_api end if (Time.now - self.updated_at) > 30 self.touch # if the last cache was more than 30 seconds ago # request api data in the background Thread.new do Rails.cache.write("#{cache_key}/#{path}",get_stuff_from_api) end end |
filter nested json column on multiple values rails Posted: 03 Jan 2017 05:10 AM PST The JSON which is stored in the database column looks similar to "data": { "player": { "firstName": "John", "lastName": "Doe", "team": "London Blues" } } and in my view I would like to have a search field, which accepts first name last name or a team name and filters the list accordingly. At the moment I have the following solution which I am not really satisfied and if there is any better ways to do it please share :) PlayerReqeust.where("initial -> 'data' -> 'player' ->> 'firstName' LIKE ? or initial -> 'data' -> 'player' ->> 'lastName LIKE ? or initial -> 'data' -> 'player' ->> 'team LIKE ?", "%John%", "%John%", "%John%") |
How to perform server-side filtering on a boolean column using Datatables.Buttons? Posted: 03 Jan 2017 04:12 AM PST I am adding Datatables to a Rails app, broadly following this Railscast (though adjusted to reflect syntax changes in recent versions of Datatables). The table has a boolean "approved" column. Using the Datatables Buttons extension, I want to add buttons to the table to filter records where approved = true or false. However I've been unable to find documentation that explains what buttons expects to receive to perform manipulations on the data. What I have so far (where data[6] is the 'approved' column): $elm = $('#toggle_table') $elm.DataTable 'processing': true 'serverSide': true 'ajax': $elm.data('url') buttons: [ { text: 'Approved' action: (e, dt, node, config) -> $.fn.dataTable.ext.search.push (settings, data, dataIndex) -> data[6] == true table.draw() $.fn.dataTable.ext.search.pop() } ] However, while the logs appear to indicate that a request is sent to the server (NB server side processing), the table data is not changed. Also, I assume the params sent to the server should include the search term, which they don't: Parameters: {"draw"=>"3", "columns"=>{....."6"=>{...."search"=>{"value"=>"", "regex"=>"false"}} What function does the Buttons extension expect to see here? Is Datatables clever enough to realize that the search function defined in the button action should be handled server side? Or do I need to explicitly define an ajax function here? |
Deploying rails application bitnami rubystack GoDaddy Posted: 03 Jan 2017 04:19 AM PST I am new to using stacks such as those from Bitnami. I recently created a Bitnami RubyStack on GoDaddy, cloned my repository and did all the house cleaning. When i SSH into the server and run rails s -b MY_PUBLIC_ip -p PORT in the application directory and i open the browser, it works perfectly fine but when i close the SSH session and point to the same address there is nothing. The public IP still shows the welcome page. I think i misunderstood the whole concept. Can someone please help teach me how it is done. Thanks in advance. Update I heard something about creating virtual hosts but cant understand how the rails s command will run. Is it possible to start the server and it continues running even when the SSH session is closed. |
Get data from Helper or use Model in Rails Posted: 03 Jan 2017 04:09 AM PST In my Rails app when creating a new Article I need a list of Users and Categories for some drop-downs so that I can choose both a category and an author for the Article. Currently I do this in the controller: def new @article = Article.new @categories = Category.order('title asc').collect { |t| [t.title, t.id] } @users = User.order('email asc').collect { |t| [t.email, t.id] } end And then in the view: <%= f.select :category_id, options_for_select(@categories), :prompt => '-- Please Select --', :required => true %> But according to RubyDocs this is bad practice, and it's not very DRY as I then have to do this for the edit method too. To prevent this, I have two possible alternatives I can think of: 1.) Use a helper like this: def users_for_select User.order('email asc').collect { |t| [t.email, t.id] } end def categories_for_select Category.order('title asc').collect { |t| [t.title, t.id] } end And then in the view: <%= f.select :category_id, options_for_select(categories_for_select), :prompt => '-- Please Select --', :required => true %> 2.) Move it to a Model: def self.categories_for_select Category.order('title asc').collect { |t| [t.title, t.id] } end def self.users_for_select User.order('email asc').collect { |t| [t.email, t.id] } end And then in the controller do this: def new @article = Article.new @categories = Category.categories_for_select @users = User.users_for_select end Option 1 feels cleaner as it removes the code from the controller, but I was under the impression that option 2 would be better as it uses a Model for data (as intended) and the controller is still sending the data (again as intended) but more DRY. I feel their is a sometimes some overlap between Helpers and Models for getting data. |
Forms with Select2 are duplicated when clicking back button on browser in Rails 5 Posted: 03 Jan 2017 03:36 AM PST _header.html.erb (for forms part) <%= form_for home_path, class: 'home', role: 'search', method: :get do |f| %> <div class="form-group" style="display:inline;"> <div class="input-group input-group-md"> <%= text_field_tag :q, params[:q], placeholder: ... ,class: 'form-control hideOverflow', type: "search" %> <%= select_tag "category", options_from_collection_for_select(...),include_blank: true, class: 'form-control hideOverflow', type: "search" %> <%if logged_in? %> <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', type: "search" %> <% else %> <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', include_blank: true, type: "search" %> <% end %> <span class="input-group-addon"><%= submit_tag "Search", class: "btn-transparent"%></span> </div> </div> <% end %> JS codes <script> $( document ).on('turbolinks:load', function() { $('select#category').select2({ width: '60%', dropdownAutoWidth : true, placeholder: "Choose a category", maximumSelectionLength: 3 }); $('select#location').select2({ width: '40%', dropdownAutoWidth : true, minimumResultsForSearch: Infinity }); }); </script> Glitch or rendering issues (click links to view the images) normal after I click back button from the browser Can someone help me out why? Plus, my search forms are in the navigation bar in header partial file. |
Thanks for the useful steps. I usually pay good attention to how actively plugin is maintained & how often plugin supports questions are answered in the forum.
ReplyDeleteAnalytics tag manager