Rails has_many but unique on associated model's column Posted: 24 Mar 2016 07:19 AM PDT I have a User model: class User < ActiveRecord::Base has_many :products end and a Product model: class Product < ActiveRecord::Base belongs_to :user end The Product table has a column named product_id which is alpha-numeric and I want that a user can have many products but should be unique on product_id . I can add an index on product_id to be unique but that would mean another user can't have a similar product. To simplify the problem, there should be a unique entry per user_id and product_id . Is there any conventional method to achieve the same in Rails ? |
Can't update rspec-rails Posted: 24 Mar 2016 07:15 AM PDT When I run bundle outdated I get: Outdated gems included in the bundle: * airbrake (newest 5.2.2, installed 4.3.6, requested ~> 4.3.4) in group "default" * jquery-rails (newest 4.1.1, installed 4.1.0) in group "default" * rspec-rails (newest 3.4.2, installed 3.1.0) in group "test" * autoprefixer-rails (newest 6.3.4, installed 6.3.1) * coderay (newest 1.1.1, installed 1.1.0) * has_scope (newest 0.7.0, installed 0.6.0) * jwt (newest 1.5.3, installed 1.5.1) * mail (newest 2.6.4, installed 2.6.3) * mime-types (newest 3.0, installed 2.99.1) * mimemagic (newest 0.3.1, installed 0.3.0) * mini_portile2 (newest 2.1.0, installed 2.0.0) * net-ssh (newest 3.1.1, installed 3.0.2) * rspec-core (newest 3.4.4, installed 3.1.7) * rspec-expectations (newest 3.4.0, installed 3.1.2) * rspec-mocks (newest 3.4.1, installed 3.1.3) * rspec-support (newest 3.4.1, installed 3.1.2) * sprockets-rails (newest 3.0.4, installed 3.0.3) * sshkit (newest 1.9.0, installed 1.8.1) I wanted to update rspec-rails with bundle update rspec-rails but the version is still 3.1.0. Why? I also tried: bundle update rspec-core rspec-expectations rspec-mocks rspec-support rspec-rails It didn't help. My Gemfile: # frozen_string_literal: true source 'https://rubygems.org' # Core gem 'rails', '5.0.0.beta3' gem 'pg' gem 'redis' gem 'puma' gem 'config' # Assets gem 'uglifier' gem 'sass-rails' gem 'slim-rails' gem 'coffee-rails' gem 'jquery-rails' gem 'bootstrap-sass' # Other gem 'paperclip' gem 'devise', '4.0.0.rc2' gem 'omniauth-facebook' gem 'activeadmin', github: 'activeadmin' gem 'airbrake', '~> 4.3.4' gem 'acts-as-taggable-on', github: 'mbleigh/acts-as-taggable-on' gem 'kaminari', github: 'amatsuda/kaminari', branch: '0-17-stable' group :test, :development do gem 'rspec-rails' end group :test do gem 'factory_girl_rails' gem 'database_cleaner' gem 'shoulda-matchers' gem 'simplecov', require: false end group :development do gem 'capistrano', '~> 3.4' gem 'capistrano-rvm' gem 'capistrano-bundler' gem 'capistrano-rails' gem 'better_errors' gem 'binding_of_caller' gem 'byebug' gem 'awesome_print' gem 'rubocop' end Gemfile.lock: GIT remote: git://github.com/activeadmin/activeadmin.git revision: 8b80ddad36bd1ba8ab0bb9ac8593d409e0fcbbf9 specs: activeadmin (1.0.0.pre2) arbre (~> 1.0, >= 1.0.2) bourbon coffee-rails formtastic (~> 3.1) formtastic_i18n inherited_resources (~> 1.6) jquery-rails jquery-ui-rails kaminari (~> 0.15) rails (>= 3.2, < 5.0) ransack (~> 1.3) sass-rails sprockets (< 4) GIT remote: git://github.com/amatsuda/kaminari.git revision: 1002b14aee62d4360c383ae1f14f5b5b72e76e2a branch: 0-17-stable specs: kaminari (0.17.0.alpha) actionpack (>= 3.0.0) activesupport (>= 3.0.0) GIT remote: git://github.com/mbleigh/acts-as-taggable-on.git revision: dde41a4d0d14e0f5b57c685265f68545383f70fa specs: acts-as-taggable-on (3.5.0) activerecord (>= 3.2, < 5) GEM remote: https://rubygems.org/ specs: actioncable (5.0.0.beta3) actionpack (= 5.0.0.beta3) nio4r (~> 1.2) websocket-driver (~> 0.6.1) actionmailer (5.0.0.beta3) actionpack (= 5.0.0.beta3) actionview (= 5.0.0.beta3) activejob (= 5.0.0.beta3) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (5.0.0.beta3) actionview (= 5.0.0.beta3) activesupport (= 5.0.0.beta3) rack (~> 2.x) rack-test (~> 0.6.3) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (5.0.0.beta3) activesupport (= 5.0.0.beta3) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) activejob (5.0.0.beta3) activesupport (= 5.0.0.beta3) globalid (>= 0.3.6) activemodel (5.0.0.beta3) activesupport (= 5.0.0.beta3) activerecord (5.0.0.beta3) activemodel (= 5.0.0.beta3) activesupport (= 5.0.0.beta3) arel (~> 7.0) activesupport (5.0.0.beta3) concurrent-ruby (~> 1.0) i18n (~> 0.7) minitest (~> 5.1) tzinfo (~> 1.1) airbrake (4.3.6) builder multi_json arbre (1.0.3) activesupport (>= 3.0.0) arel (7.0.0) ast (2.2.0) autoprefixer-rails (6.3.1) execjs json awesome_print (1.6.1) bcrypt (3.1.11) better_errors (2.1.1) coderay (>= 1.0.0) erubis (>= 2.6.6) rack (>= 0.9.0) binding_of_caller (0.7.2) debug_inspector (>= 0.0.1) bootstrap-sass (3.3.6) autoprefixer-rails (>= 5.2.1) sass (>= 3.3.4) bourbon (4.2.6) sass (~> 3.4) thor (~> 0.19) builder (3.2.2) byebug (8.2.2) capistrano (3.4.0) i18n rake (>= 10.0.0) sshkit (~> 1.3) capistrano-bundler (1.1.4) capistrano (~> 3.1) sshkit (~> 1.2) capistrano-rails (1.1.6) capistrano (~> 3.1) capistrano-bundler (~> 1.1) capistrano-rvm (0.1.2) capistrano (~> 3.0) sshkit (~> 1.2) climate_control (0.0.3) activesupport (>= 3.0) cocaine (0.5.8) climate_control (>= 0.0.3, < 1.0) coderay (1.1.0) coffee-rails (4.1.1) coffee-script (>= 2.2.0) railties (>= 4.0.0, < 5.1.x) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.10.0) concurrent-ruby (1.0.1) config (1.1.0) activesupport (>= 3.0) deep_merge (~> 1.0.1) database_cleaner (1.5.1) debug_inspector (0.0.2) deep_merge (1.0.1) devise (4.0.0.rc2) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 5.1) responders warden (~> 1.2.3) diff-lcs (1.2.5) docile (1.1.5) erubis (2.7.0) execjs (2.6.0) factory_girl (4.5.0) activesupport (>= 3.0.0) factory_girl_rails (4.6.0) factory_girl (~> 4.5.0) railties (>= 3.0.0) faraday (0.9.2) multipart-post (>= 1.2, < 3) formtastic (3.1.3) actionpack (>= 3.2.13) formtastic_i18n (0.6.0) globalid (0.3.6) activesupport (>= 4.1.0) has_scope (0.6.0) actionpack (>= 3.2, < 5) activesupport (>= 3.2, < 5) hashie (3.4.3) i18n (0.7.0) inherited_resources (1.6.0) actionpack (>= 3.2, < 5) has_scope (~> 0.6.0.rc) railties (>= 3.2, < 5) responders jquery-rails (4.1.0) rails-dom-testing (~> 1.0) railties (>= 4.2.0) thor (>= 0.14, < 2.0) jquery-ui-rails (5.0.5) railties (>= 3.2.16) json (1.8.3) jwt (1.5.1) loofah (2.0.3) nokogiri (>= 1.5.9) mail (2.6.3) mime-types (>= 1.16, < 3) method_source (0.8.2) mime-types (2.99.1) mimemagic (0.3.0) mini_portile2 (2.0.0) minitest (5.8.4) multi_json (1.11.2) multi_xml (0.5.5) multipart-post (2.0.0) net-scp (1.2.1) net-ssh (>= 2.6.5) net-ssh (3.0.2) nio4r (1.2.1) nokogiri (1.6.7.2) mini_portile2 (~> 2.0.0.rc2) oauth2 (1.1.0) faraday (>= 0.8, < 0.10) jwt (~> 1.0, < 1.5.2) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.3.1) hashie (>= 1.2, < 4) rack (>= 1.0, < 3) omniauth-facebook (3.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.4.0) oauth2 (~> 1.0) omniauth (~> 1.2) orm_adapter (0.5.0) paperclip (4.3.6) activemodel (>= 3.2.0) activesupport (>= 3.2.0) cocaine (~> 0.5.5) mime-types mimemagic (= 0.3.0) parser (2.3.0.6) ast (~> 2.2) pg (0.18.4) polyamorous (1.3.0) activerecord (>= 3.0) powerpack (0.1.1) puma (3.2.0) rack (2.0.0.alpha) json rack-test (0.6.3) rack (>= 1.0) rails (5.0.0.beta3) actioncable (= 5.0.0.beta3) actionmailer (= 5.0.0.beta3) actionpack (= 5.0.0.beta3) actionview (= 5.0.0.beta3) activejob (= 5.0.0.beta3) activemodel (= 5.0.0.beta3) activerecord (= 5.0.0.beta3) activesupport (= 5.0.0.beta3) bundler (>= 1.3.0, < 2.0) railties (= 5.0.0.beta3) sprockets-rails (>= 2.0.0) rails-deprecated_sanitizer (1.0.3) activesupport (>= 4.2.0.alpha) rails-dom-testing (1.0.7) activesupport (>= 4.2.0.beta, < 5.0) nokogiri (~> 1.6.0) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.3) loofah (~> 2.0) railties (5.0.0.beta3) actionpack (= 5.0.0.beta3) activesupport (= 5.0.0.beta3) method_source rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rainbow (2.1.0) rake (11.1.1) ransack (1.7.0) actionpack (>= 3.0) activerecord (>= 3.0) activesupport (>= 3.0) i18n polyamorous (~> 1.2) redis (3.2.2) responders (2.1.2) railties (>= 4.2.0, < 5.1) rspec-core (3.1.7) rspec-support (~> 3.1.0) rspec-expectations (3.1.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.1.0) rspec-mocks (3.1.3) rspec-support (~> 3.1.0) rspec-rails (3.1.0) actionpack (>= 3.0) activesupport (>= 3.0) railties (>= 3.0) rspec-core (~> 3.1.0) rspec-expectations (~> 3.1.0) rspec-mocks (~> 3.1.0) rspec-support (~> 3.1.0) rspec-support (3.1.2) rubocop (0.38.0) parser (>= 2.3.0.6, < 3.0) powerpack (~> 0.1) rainbow (>= 1.99.1, < 3.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.7.5) sass (3.4.21) sass-rails (5.0.4) railties (>= 4.0.0, < 5.0) sass (~> 3.1) sprockets (>= 2.8, < 4.0) sprockets-rails (>= 2.0, < 4.0) tilt (>= 1.1, < 3) shoulda-matchers (3.1.1) activesupport (>= 4.0.0) simplecov (0.11.2) docile (~> 1.1.0) json (~> 1.8) simplecov-html (~> 0.10.0) simplecov-html (0.10.0) slim (3.0.6) temple (~> 0.7.3) tilt (>= 1.3.3, < 2.1) slim-rails (3.0.1) actionmailer (>= 3.1, < 5.0) actionpack (>= 3.1, < 5.0) activesupport (>= 3.1, < 5.0) railties (>= 3.1, < 5.0) slim (~> 3.0) sprockets (3.5.2) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.0.3) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sshkit (1.8.1) net-scp (>= 1.1.2) net-ssh (>= 2.8.0) temple (0.7.6) thor (0.19.1) thread_safe (0.3.5) tilt (2.0.2) tzinfo (1.2.2) thread_safe (~> 0.1) uglifier (3.0.0) execjs (>= 0.3.0, < 3) unicode-display_width (1.0.2) warden (1.2.6) rack (>= 1.0) websocket-driver (0.6.3) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.2) PLATFORMS ruby DEPENDENCIES activeadmin! acts-as-taggable-on! airbrake (~> 4.3.4) awesome_print better_errors binding_of_caller bootstrap-sass byebug capistrano (~> 3.4) capistrano-bundler capistrano-rails capistrano-rvm coffee-rails config database_cleaner devise (= 4.0.0.rc2) factory_girl_rails jquery-rails kaminari! omniauth-facebook paperclip pg puma rails (= 5.0.0.beta3) redis rspec-rails rubocop sass-rails shoulda-matchers simplecov slim-rails uglifier BUNDLED WITH 1.11.2 |
Reload javascript when validation fails upon update and still show validation errors Posted: 24 Mar 2016 07:13 AM PDT I am using the nested_form_fields gem. I have the following associations to allow a contact to have associations to multiple teams : #models/contact.rb class Contact < ActiveRecord::Base has_many :contacts_teams has_many :teams, through: :contacts accepts_nested_attributes_for :contacts_teams, allow_destroy: true end #models/contacts_team.rb class ContactsTeam < ActiveRecord::Base belongs_to :contact belongs_to :team end #models/team.rb class Team < ActiveRecord::Base has_many :contacts_team has_many :contacts, through: :contacts_teams end A contact always Must have at least one team . I created a custom validation which checks for this when the user is creating a new contact or is updating an existing contact . #custom validation within models/contact.rb class Contact < ActiveRecord::Base ... validate :at_least_one_contacts_team private def at_least_one_contacts_team # when creating a new contact: making sure at least one team exists return errors.add :base, "Must have at least one Team" unless contacts_teams.length > 0 # when updating an existing contact: Making sure that at least one team would exist return errors.add :base, "Must have at least one Team" if contacts_teams.reject{|contacts_team| contacts_team._destroy == true}.empty? end end It works for the most part. But there is an edge when updating an existing contact's team. Here I am updating a contact and it shows that they have two existing associated teams: The user clicks the X's next to each team in order to delete them, so they no longer show on the page, and then the user clicks update to put these changes into effect: The validation properly fails because the user attempted to delete all the associated teams. It properly shows the validation error message: However, the problem is that the form does not redisplay the existing associated teams! Those associations have not been deleted yet, so they should still show: How do I show existing team associations after validations fail when updating an existing contact? I attempted removing all the _destroy flags in hopes that by doing so those associated teams will show. Unfortunately it didn't do the trick: # block run when update validation fails else params[:contact][:contacts_teams_attributes].each do |k,v| v.delete_if{|k,v| k == "_destroy" && v == "1"} end render :edit end I am thinking that the page is remembering the javascript that was run previously. So it remembers that the teams were marked to be deleted so is not rendering them. I don't know how to reset the javascript unless I do a redirect , in which case all the validation errors will no longer be shown. Thanks in advance! |
Rails and Rack::Protection::AuthenticityToken Posted: 24 Mar 2016 07:16 AM PDT I'm having some difficulty to implement the rack-protection gem with rails. The AuthenticityToken protection was enabled in that way: #application.rb module MyApp class Application < Rails::Application config.middleware.use Rack::Protection config.middleware.use Rack::Protection::AuthenticityToken end end The problem is that I aways get a "Forbidden" when logging with Devise gem. WARN -- : attack prevented by Rack::Protection::AuthenticityToken However the "csrf_meta_tags" are present on the top of every page: <head> <meta name="csrf-param" content="authenticity_token"> <meta name="csrf-token" content="+4lRTVfIWBjsgGXEzHFVCIf/Bi/jqqfkLPg6qdw5FMHA1L3Eh36I+hALcRIhv1VjfgTznssJqvRh+/IEMhyNeA=="> </head> And the authenticity_token is passed as an input hidden inside the session form too: <input name="authenticity_token" value="+4lRTVfIWBjsgGXEzHFVCIf/Bi/jqqfkLPg6qdw5FMHA1L3Eh36I+hALcRIhv1VjfgTznssJqvRh+/IEMhyNeA==" type="hidden"> What am I missing here? I'm in development mode, not production. Thanks! |
cpanel and mod passenger with PassengerMinInstances 1 not working Posted: 24 Mar 2016 07:00 AM PDT im using centos 6 with cpanel with mod passenger. i tried to configure extra custom apache configuration for a domain, and vi /usr/local/apache/conf/userdata/std/2/username/domain.com/rails.conf and configured: PassengerMinInstances 1 PassengerMaxPoolSize 3 but the instance seems to auto shutdown after 5minutes of inactive anyone encounter similar issue? |
Rails flash: concurrency problems Posted: 24 Mar 2016 07:13 AM PDT I have written and maintain a Rails forum software. In this software I redirect the user to the posting URL with a notice that the posting has been saved. Just before that I send a notification via a websocket to notify the users that a new posting or thread has arrived and the possibly in a different tab opened thread list can get updated. To update the thread list I do an AJAX request to the server and fetch the new, fresh thread tree. This leads to the weird phenomenon that the flash doesn't clear after it gets displayed. It only clears when I close all tabs but one and do a manual reload. After a lot of debugging it seems to me that there is a race condition with the session cookie. Due to the AJAX request the flash gets set again and again: - Request 1 clears the flash in the session cookie
- before Request 1 has been finished Request 2 starts with the old flash content in the session cookie
- when Request 1 has finished it sets the local cookie value to the new value
- Request 2 finishes and sets the local cookie value back to the old value
A temporary solution to the problem is to delay the AJAX request. This works, but is still vulnerable to the same race condition, depending on net speed. But I could not find a real solution to this problem; any suggestions? |
Rails project after db:create, error message: "dyld: lazy symbol binding failed: Symbol not found" Posted: 24 Mar 2016 07:32 AM PDT I git cloned a project and, after bundle install , I tried a db:create but I have this error message. Does anyone know where it is coming from? ➜ ******* git:(master) ✗ bundle exec rake db:create [2.3.0] dyld: lazy symbol binding failed: Symbol not found: __ZN2v82V821AddGCPrologueCallbackEPFvNS_6GCTypeENS_15GCCallbackFlagsEES1_ Referenced from: /Users/zato/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/therubyracer-0.12.2/lib/v8/init.bundle Expected in: flat namespace dyld: Symbol not found: __ZN2v82V821AddGCPrologueCallbackEPFvNS_6GCTypeENS_15GCCallbackFlagsEES1_ Referenced from: /Users/zato/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/therubyracer-0.12.2/lib/v8/init.bundle Expected in: flat namespace |
Rails + Koala gem publish post in my personal page from my personal site Posted: 24 Mar 2016 06:51 AM PDT I have a Facebook page and I want to publish post in the wall from my personal site. I am using Koala: user = Koala::Facebook::API.new user_access_token page_access_token = user.get_connections('me', 'accounts').first['access_token'] page = Koala::Facebook::API.new page_access_token page.put_connections("me", "feed", message: "I am posting on my page!ok!") Problem: when I go in my page I see the posts just published from my site but if I visit the Facebook page with an other Facebook account the page is empty and there is no post!! I think is a visibility problem but I am not resolving. |
How to call controller action and then render it to a string in ror? Posted: 24 Mar 2016 07:14 AM PDT How to call controller action and then render in to a string from "outside" in ror? class SomeService controller = UsersController.new # need to call an index action # data = controller.render_to_string end |
An error occurred while installing autoprefixer-rails (6.2.2). Additionally it say's "autoprefixer-rails requires ruby version >= 2.0. " Posted: 24 Mar 2016 06:48 AM PDT Im facing this problem when i'm installing bunder using command "bunlde install" Initially i tried solving this issue by using following command gem install autoprefixer-rails -v '6.2.2' but again it said "autoprefixer-rails requires ruby version >= 2.0." when i type "ruby -v", my ruby version shows 2.3.0. Next i have tried adding ruby '2.3.0' to my gem file, then there was a conflict saying your ruby version is 1.9.3 but your gem file has 2.3.0 Need help how to proceed further. |
How do I test a csv file upload in rails 5? Posted: 24 Mar 2016 06:35 AM PDT I've looked at a ton of ways to do this, but haven't had any luck. Everything suggests using fixture_file_upload. So I'm using that in my tests. However when I look in the controller, the file's :tempfile is an array of strings which is the full content of the csv. However when I upload a file using postman the :tempfile is some sort of file object. POST via test results in: [1] pry(#<API::V1::ImportsController>)> params[:file] => <ActionController::Parameters {"content_type"=>"text/csv", "original_filename"=>"data_import.csv", "tempfile"=>["name, age\n", "bob, 4\n", "steve, 8\n", "mike, 9\n", "amy, 2\n", "nicole, 4\n"]} permitted: false> POST via postman results in: [1] pry(#<API::V1::ImportsController>)> params[:file] => #<ActionDispatch::Http::UploadedFile:0x007ffbe34b6e00 @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"data_import.csv\"\r\nContent-Type: text/csv\r\n", @original_filename="data_import.csv", @tempfile=#<File:/var/folders/s5/0qnd62ld5pg3x7qq9my30cqm0000gn/T/RackMultipart20160324-62301-1gwxwy9.csv>> |
Rake error : Don't know how to build task Posted: 24 Mar 2016 06:54 AM PDT Please I have a problem when I want to build task. When I use $rake export it generates the following error: rake aborted! Don't know how to build task 'test:export' /Users/metoui/.rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in eval' /Users/metoui/.rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in ' the export.rake is require 'yaml' namespace :export do namespace :company_application do desc "TODO" task :run => :environment do csv_filename = "log/#{Time.now.strftime("%Y%m%d")}- companies_domains.csv" cmd = "touch #{csv_filename}" system(cmd) target = File.open(csv_filename, 'w') target.write("company_id;company;name;contractual_name;company_type;status;statistic_color;deal_id;billing;billing_start;app_id;environment_type;platform;") target.write("\n") per_batch = 50 0.step(Company.only(:id).count, per_batch) do |offset| Company.all.limit(per_batch).skip(offset).each do |comp| comp.domains.each do |dom| c_id = comp.id c_company = comp.try(:name).gsub(/[^0-9a-zA-Z_]/, ' ').gsub(' ','_').to_s || " " c_name = comp.try(:trylive_name) || " " c_contractual_name = comp.try(:contractual_name) || " " c_company_type = comp.try(:type) || " " c_status = comp.try(:status) || " " c_color_stat = comp.try(:statistic_color) || " " c_deal_id = comp.try(:invoicing_id) || " " c_billing = comp.try(:billing) || " " c_billing_start = comp.try(:billing_start) || " " d_app_id = dom.try(:appid) || " " d_env_type = dom.try(:environment_type) || " " d_domain_type = dom.try(:type) || " " target.write("#{c_id};#{c_company};#{c_name};#{c_contractual_name};#{c_company_type};#{c_status};#{c_color_stat};#{c_deal_id};#{c_billing};#{c_billing_start};#{d_app_id};#{d_env_type};#{d_domain_type};") target.write("\n") end end sleep(1) end target.close() dest_path = "data_recorder/#{env_folder}csv_exports/companies_domains/#{Time.now.strftime("%Y%m%d")}-companies_domains_list.csv" response = upload_csv_to_s3 path: dest_path, file: csv_filename, acl: "authenticated-read" dest_path = "data_recorder/#{env_folder}csv_exports/companies_domains/latest/companies_domains_list.csv" response = upload_csv_to_s3 path: dest_path, file: csv_filename, acl: "authenticated-read" if response print "File uploaded \n" system("rm #{csv_filename}") system "echo 'Success export: #{Time.now.strftime("%Y%m%d")} - #{response.inspect}' >> log/csv_export.log" else print "Something wrong happened \n" system "echo 'error export: #{Time.now.strftime("%Y%m%d")} - #{response.inspect}' >> log/csv_export.log" print response.inspect end end end |
Cannot access "Current user" in rails Posted: 24 Mar 2016 07:20 AM PDT I am using devise and devise_ldap for my rails authentication. I am trying to use the built in helper, current user to display the users email on the welcome page of my application. This is the code that I have tried to use to: <% if user_signed_in? %> <div>Signed in as... <%= current_user.email %></div> <% end %> when I sign in to the application, I get the error; undefined method `email' for nil:NilClass Here is my routes.rb Rails.application.routes.draw do devise_for :users resources :users resources :systems do member do get :targets, :sources end root 'systems#index' end and my users controller: class UsersController < ApplicationController authorize_resource before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users def index @users = User.all.order("display_name asc") end # GET /users/1 def show end # GET /users/new def new @user = User.new end # GET /stories/1/edit def edit respond_to do |format| format.html format.js end end # POST /stories def create @user = User.new(user_params) respond_to do |format| puts 'user controller' if @user.save! format.html { redirect_to user_path(@user), notice: 'User was successfully created.' } else format.html { render :new } end end end # PATCH/PUT /stories/1 def update respond_to do |format| if @user.update(user_params) format.html { redirect_to user_path(@user), notice: 'User was successfully updated.' } else format.html { render :edit } end end end # DELETE /stories/1 def destroy @user.destroy respond_to do |format| format.html { redirect_to users_path notice: 'User was successfully destroyed.' } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:display_name, :email, :username) end end my users model: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable before_create :rememberable_value before_save :get_ldap_values devise :ldap_authenticatable, :rememberable, :trackable, :validatable def get_ldap_values if self.username self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first if Devise::LDAP::Adapter.get_ldap_param(self.username,"mail") self.display_name = Devise::LDAP::Adapter.get_ldap_param(self.username,"displayName").first if Devise::LDAP::Adapter.get_ldap_param(self.username,"displayName") end end # def role?(role) # return !!self.roles.find_by_name(role.to_s.camelize) # end def email_required? false end def email_changed? false end def rememberable_value self.remember_token ||= Devise.friendly_token end def name_to_display if self.display_name self.display_name else self.username end end def password_required? false end def password_match? self.errors[:password] << "can't be blank" if password.blank? self.errors[:password_confirmation] << "can't be blank" if password_confirmation.blank? self.errors[:password_confirmation] << "does not match password" if password != password_confirmation password == password_confirmation && !password.blank? end end I am not sure what I am missing to be able to access the current users information after a successful sign in. Update Here is the new routes file: Rails.application.routes.draw do devise_scope :user do get '/users/sign_out' => 'devise/sessions#destroy' get "/users/sign_in" => "devise/sessions#new" # delete "/logout" => "devise/sessions#destroy" end devise_for :users authenticate(:user) do resources :users resources :reports resources :change_logs, only: [:index, :show] resources :systems do member do get :targets, :sources end resources :change_logs, module: :systems resources :components do resources :change_logs, module: :components end resources :c_relations end resources :integrations get '/static_pages/home' # => 'static_pages#home', as: 'home' root 'systems#index' end |
SQL/ActiveRecord nested joins query to return results only if all rows match a range Posted: 24 Mar 2016 06:30 AM PDT I've tried to find the answer for couple of days but haven't found it. Please advise: For example: - I have
User , Cupboards , Shelf and Book models in my project. - Above models connected with relation
:has_many (User :has_many Cupboards , .. , Shelf :has_many Books ) Book has property - :color I need to find Users who have only yellow or red books. I built such query but it returns users which have at list one yellow or red book: User.joins(:cupboard => {:shelfs => :books}).where("books.color IN (?)", %w(red yellow) Thanks in advance for your help guys! |
Where should I put my page related javascript code in Rails 3.2 using jQuery? Posted: 24 Mar 2016 06:27 AM PDT I'm using JQuery and Highcharts. Here it is my app/assets/javascripts/ folder's content : application.js graphique_repartition_budgetaire.js.erb proj_charge.js.erb Here it is my app/assets/javascripts/application.js file // This is a manifest file ... bla bla bla ... // //= require jquery //= require jquery_ujs //= require_tree . //= require highcharts Here it is my app/assets/javascripts/graphique_repartition_budgetaire.js.erb file $(function () { Highcharts.setOptions({ lang: { thousandsSep: "'" } }); $('#graphique-repartition-budgetaire').highcharts({ // my graphic code is here.... }); }); Until there it's working fine. The problems rise when I try to code other javascript/JQuery for an other specific page. I put this new code into a file app/assets/javascripts/proj_charge.js.erb : $(function () { alert('JQuery is ready !'); }); This file doesn't execute and doesn't seem to be loaded either. Why ? Should I put all my jQuery code into the same file ? I'm a beginnner with Javascript and JQuery so I dont know if maybe it is forbidden to declare twice the same $(function () {}); What am I doign wrong ? |
Creating User Pages Rails Scaffold issue Posted: 24 Mar 2016 07:20 AM PDT im making a web app in which i have made two scaffolds user pages and page posts , but i have a problem that is how do i put the page posts index page on user pages show.html.erb and how do I filter them with the users specific for the user pages |
Precompiled assets not being used Posted: 24 Mar 2016 06:11 AM PDT I deployed my Rails application to an nginx server. When i go to the Page i can see the precompiled js and css assets including their fingerprints in the filename. I can also navigate to them in the browser but none of the js functions work. Neither the one that come along with CKEditor or Bootstrap-Datepicker nor the functions i've written by my self. Safari returns ReferenceError: Can't find variable: CKEDITOR Firefox: ReferenceError: CKEDITOR is not defined In local development mode it works just fine. The really confusing part for me is, that the precompiled css is working perfectly. I'm using coffeScript with the coffee-rails gem (v. 4.1.1) and jquery-rails (v 4.1.0) For the deploy i use capistrano (v 3.4.0) Rails version is 4.2.4 |
How do I remove the Devise route to cancel an account? Posted: 24 Mar 2016 06:09 AM PDT For default, when show User account have a field for cancel/remove your account, how I make for disabled this in routes? For now, I have this routes: devise_scope :usuario do get "/usuarios/sign_up", :to => "home#index" end devise_for :usuarios, controllers: { registrations: "usuarios/registrations" } Thanks! |
Duplicated business logic in Ruby and SQL Posted: 24 Mar 2016 06:41 AM PDT I have a PORO (Plain Old Ruby Object) to deal with some business logic. It receives an ActiveRecord object and classify it. For the sake of simplicity, take the following as an example: class Classificator STATES = { 1 => "Positive", 2 => "Neutral", 3 => "Negative" } def initializer(item) @item = item end def name STATES.fetch(state_id) end private def state_id return 1 if @item.value > 0 return 2 if @item.value == 0 return 3 if @item.value < 0 end end However, I also want to do queries that groups objects based on these state_id "virtual attribute". I'm currently dealing with that by creating this attribute in the SQL queries and using it in GROUP BY statements. See the example: class Classificator::Query SQL_CONDITIONS = { 1 => "items.value > 0", 2 => "items.value = 0", 3 => "items.value < 0" } def initialize(relation = Item.all) @relation = relation end def count @relation.select(group_conditions).group('state_id').count end private def group_conditions 'CASE ' + SQL_CONDITIONS.map do |k, v| 'WHEN ' + v.to_s + " THEN " + k.to_s end.join(' ') + " END AS state_id" end end This way, I can get this business logic into SQL and make this kind of query in a very efficient way. The problem is: I have duplicated business logic. It exists in "ruby" code, to classify a single object and also in "SQL" to classify a collection of objects in database-level. Is it a bad practice? Is there a way to avoid this? I actually was able to do this, doing the following: item = Item.find(4) items.select(group_conditions).where(id: item.id).select('state_id') But by doing this, I loose the ability to classify objects that are not persisted in database. The other way out would be classifying each object in ruby, using an Iterator, but then I would lose database performance. It's seem to be unavoidable to keep duplicated business logic if I need the best of the two cases. But I just want to be sure about this. :) Thanks! |
Get Cloudinary image URL Posted: 24 Mar 2016 06:09 AM PDT I have a model called Tile, and it has attachment: has_attachment :image_attachment I can use cl_image_tag @tile.image_attachment.path to display img tag but I want to get only full URL to embed is an background image in inline style, is there a way to get full URL? ``@tile.image_attachment.path returns v1458814322/bgo1zuv4kji17f58x5m5.jpg |
Rails, Active Admin, Devise, routes Posted: 24 Mar 2016 06:06 AM PDT I've been working with Rails, Active Addmin and cancancan. Everything is working fine except one thing. Recently I have added separate namespaces for my admin type users and clients. Before that change, I redirected all authenticated users to the same active admin dashboard in such way (routes.rb): devise_scope :user do authenticated :user do root :to => 'admin/dashboard#index', as: :authenticated_root end unauthenticated :user do root :to => 'pages#index', as: :unauthenticated_root end end Currently I need to somehow add additional condition that will be checking if authenticated user has role admin or client. My idea was to make sth like that: devise_scope :user do authenticated :user do if current_user.role?(:Architect) || current_user.role?(:Admin) root :to => 'admin/dashboard#index', as: :authenticated_root else root :to => 'clients/dashboard#index', as: :authenticated_client end end unauthenticated :user do root :to => 'pages#index', as: :unauthenticated_root end end But I am getting error: undefined local variable or method `current_user' Does anybody know how I can check user's role in routes? Is there any better way to do that? |
How to route 2 different URL's to the same action in Rails 2? Posted: 24 Mar 2016 05:30 AM PDT I'm dealing with an application that's using Rails 2.3.18 and I'm wondering if it's possible to route multiple url's to the same action without creating a new map. map.home '/', :controller => 'pages', :action=>'home', :path=>'home' Is it possible to route to '/', as well as '/home' in this mapping? I've been having a look through the routing documentation and I can't seem to find anything that allows you to do something like this, is it possible? |
App Engine Issue Deploy Posted: 24 Mar 2016 04:05 AM PDT I have some issues with google cloud using App Engine. I deploy my rails app to my google cloud. The problem is the server returns Error: Server Error The service you requested is not available yet. Please try again in 30 seconds. And the Status Code 503. Do you guys have some tips ? |
Docker on Windows getting "Could not locate Gemfile" Posted: 24 Mar 2016 04:02 AM PDT I'm trying to learn Docker using Windows as the host OS to create a container using Rails image from Docker Hub. I've created a Dockerfile with the content below and an empty Gemfile, however I'm still getting the error "Could not locate Gemfile". Dockerfile FROM rails:4.2.6 The commands I used are the following (not understanding what they actually do though): ju.oliveira@br-54 MINGW64 /d/Juliano/ddoc $ docker build -t ddoc . Sending build context to Docker daemon 4.608 kB Step 1 : FROM rails:4.2.6 ---> 3fc52e59c752 Step 2 : MAINTAINER Juliano Nunes ---> Using cache ---> d3ab93260f0f Successfully built d3ab93260f0f SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories. $ docker run --rm -v "$PWD":/usr/src/app -w /usr/src/app ruby:2.1 bundle install Unable to find image 'ruby:2.1' locally 2.1: Pulling from library/ruby fdd5d7827f33: Already exists a3ed95caeb02: Pull complete 0f35d0fe50cc: Already exists 627b6479c8f7: Already exists 67c44324f4e3: Already exists 1429c50af3b7: Already exists f4f9e6a0d68b: Pull complete eada5eb51f5d: Pull complete 19aeb2fc6eae: Pull complete Digest: sha256:efc655def76e69e7443aa0629846c2dd650a953298134a6f35ec32ecee444688 Status: Downloaded newer image for ruby:2.1 Could not locate Gemfile So, my questions are: - Why it can't find the Gemfile if it's in the same directory as the Dockerfile?
- What does the command
docker run --rm -v "$PWD":/usr/src/app -w /usr/src/app ruby:2.1 bundle install do? - How do I set a folder in my host file system to be synced to the container (I'm trying to create a development environment for Rails projects using Docker on Windows)?
I don't know if this makes any difference, but I'm running this command from the bash executed via "Docker Quickstart Terminal" shortcut. I think all it does is run these commands in a default VM, though I could create a new one (but I don't know if I should do this). Thank you and sorry for all these questions, but right know Docker seems very confusing for me. |
Form Helpers with Ruby on Rails Posted: 24 Mar 2016 04:04 AM PDT I'm using a form helper in one of my views and I want the user to choose from a list of options. I then want to store the id equivalent for the option chosen into my database. However, every time I choose an option, its id isn't being stored and the database just says nil for this attribute. <%= f.label :"Team Against" %><br> <%= f.select :opposing_team, options_for_select([['Team 1', 1], ['Team 2', 2], ['Team 3', 3]]) %><br> For example, I have a column in my table called 'opposing_team' and when team 1 is chosen by the user, I want opposing_team to be updated with the value 1. Currently I can choose the range of options in the form but the opposing_team value is always nil. edit: def create @league = League.find(params[:league_id]) @team = @league.teams.find(params[:team_id]) @fixture = @team.fixtures.create(fixture_params) if @fixture.save redirect_to league_team_path(:league_id => @league.id, :id => @team.id) else render 'new' end end def new @team = Team.find(params[:team_id]) @fixture = Fixture.new end This is what the fixtures controller consists of. The opposing_team is an integer value in the database. |
ActiveRecord: Transform scope to arel node, with strings Posted: 24 Mar 2016 03:27 AM PDT I have this scope: scope :finished, -> { where(status: "finished") } I found that that transform a scope into an arel node is just calling #arel on it. All this because I have a complex query, and I want to reuse the conditions: table.join(.....).where(table[:id].eq(2)).where(ThatClass.finished.arel).to_sql #=> .... AND "that_classes"."status" = $1 ...... Why is 'finished' not there? How can I integrate it? This only happens with strings, as if it were an integer or a not null scope, it would print exactly as expected |
Unpermitted params customer_ids Posted: 24 Mar 2016 03:37 AM PDT Super simple, dumb thing, which I can't figure out for more, than an hour now: def user_params params.require(:user).permit(customer_ids: []) # pg array column end My form: = f.select :customer_ids, options_from_collection_for_select(customers, 'id', 'name', user.customer_ids), { include_blank: 'Select customer', multiple: true, size: 15 }, class: 'form-control' And while updating user I'm getting Unpermitted parameter: customer_ids How the heck in the world is that possible? Parameters: {"utf8"=>"✓", "authenticity_token"=>"oCkUEi2pNajM0ydHUH2w6iYIq5eKjfCY5ig9U2qDTXxMqECCgQ2Dn9YtqkMqXlTmLl5q/OO8x23o/P50SnmgUg==", "user"=>{"customer_ids"=>"84"}, "commit"=>"Assign selected customer to user", "id"=>"2"} |
Heroku - Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set) Posted: 24 Mar 2016 02:53 AM PDT I'm trying to run heroku run rake db:migrate but I continuously get this error message: Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). I have seen people say just type in Git Init, but when I type in that, I just get fatal: Not a git repository (or any parent up to mount point /app) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). fatal: Not a git repository (or any parent up to mount point /app) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). fatal: Not a git repository (or any parent up to mount point /app) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). fatal: Not a git repository (or any parent up to mount point /app) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). Kindly guide me. |
How to set a variable to nil if the user leaves their answer as blank? Posted: 24 Mar 2016 02:42 AM PDT I'm learning ruby and am a bit stuck. They want us to set a variable as nil if the user leaves the question blank. Otherwise convert their answer to an integer. I came up with the following, but when I leave the answer blank, it prints 0. Could you steer me in the right direction? puts "What's your favorite number?" number = gets.chomp if number == ' ' number = nil else number = number.to_i end p number |
Autofill text fields depending on dropbox value in Rails Posted: 24 Mar 2016 06:11 AM PDT I want to make some of my text fields to auto fill with zero(0), when the user selects NA in one dropdown.. How can I achieve that? Is there any rails way to do that?? I have seen lot of jquery to accomplish auto fill values.. But I am new to rails as well as am zero at jquery.. That is why I am looking for a rails way to do that. Kindly please someone help me. |
No comments:
Post a Comment