Concatenate bytes - Writing file to FTP folder as chunks Posted: 15 Nov 2016 07:41 AM PST I'm writing an Rails app which could upload files to storage. Big files are splitted into chunks from client (with JS) and upload parts to server. As in development, I could simply open existed file and write following bytes into that. (I'm using CarrierWave gem) File.open(@up_file.link.path, "ab") do |f| f.write(up_file_params[:link].read) end # This code worked when I upload to '/public' folder in development However, now I want to use a FTP server to storage files. But I can't Concatenate new bytes with existed bytes. def get_ftp_connection # create a new FTP connection ftp = Net::FTP.new ftp.connect(ENV['ftp_host'], ENV['ftp_port']) begin ftp.passive = ENV['ftp_passive'] ftp.login(ENV['ftp_user'], ENV['ftp_passwd']) yield ftp ensure ftp.quit end end ..... def create ..... get_ftp_connection @up_file do |ftp| full_path = ::File.dirname "#{ENV['ftp_folder']}/#{@up_file.link.path}" base_name = File.basename(@up_file.link.to_s) ftp.chdir(full_path) ftp.putbinaryfile(up_file_params[:link].read, base_name) end end I got ArgumentError (string contains null byte): at putbinaryfile... , any help :( |
Prepopulate rails form_for email_field with email address Posted: 15 Nov 2016 07:16 AM PST I have a simple email field that I want to pre-populate with the user's email when they hit the login page (assuming they followed a link there and we can identify who they are). I have: <%= f.email_field :email, autofocus: @contact.email.blank?, class: "form-control" %> I've tried doing: <%= f.email_field(@contact, @contact.email) :email, autofocus: @contact.email.blank?, class: "form-control" %> <%= f.email_field(@contact.email) :email, autofocus: @contact.email.blank?, class: "form-control" %> And also: <%= f.email_field :email, autofocus: @contact.email.blank?, class: "form-control", value: @contact.email %> But nothing seems to work. I'd like to avoid changing the field type to text if possible. |
Authorization settings using pundit gem rails Posted: 15 Nov 2016 07:03 AM PST I'm new at rails so bear with me pls. My problem is so specific. I'm creating a User blog, where they could put any posts. So Users has a blogs, and blogs has posts. So when user create a blog, all posts in his blog should be written by him. Other users can't write not on their blogs. post_controller.rb class PostsController < ApplicationController before_action :authenticate_user! before_action :authorize_user!, only: [:edit, :update, :destroy] expose :blog expose :post def show end def new end def edit end def create post.user = current_user post.save respond_with post, location: user_blog_path(post.blog.user, post.blog) end def update post.update(post_params) respond_with post, location: user_blog_path(post.blog.user, post.blog) end def destroy post.destroy respond_with post, location: user_blog_path(post.blog.user, post.blog) end private def authorize_user! authorize(post, :authorized?) end def post_params params.require(:post).permit(:title, :content, :user_id, :blog_id) end end Here i'm using pundit to authorize user, when they update or destroy posts (users can update or destroy only their own posts) and it works perfectly. views/posts/new .row .columns h2 = title("New post") .row .medium-5.columns = simple_form_for post do |f| = f.error_notification .form-inputs = f.input :title = f.input :content = f.hidden_field :blog_id, value: blog.id .form-actions = f.button :submit Here i'm using the hidden form to set the blog_id which I take from params. Http link looks like http://localhost:3000/posts/new?blog_id=6. The problem is that each user can copy this link to create the post( and they are not the blog owners). post_policy.rb class PostPolicy < ApplicationPolicy def authorized? record.user == user end end How should I check the blog's owner before post creating? Maybe I have a wrong way to create posts like this(using hidden form). Link to create new post = link_to 'New Post', new_post_path(blog_id: blog.id) |
Rails Generate migration throwing error Posted: 15 Nov 2016 06:57 AM PST i added a gem "acts-as-taggable-on" and when i ran the rails g acts_as_taggable_on:migration command. i got this Could not find generator 'acts_as_taggable_on:migration'. Maybe you meant 'active_record:migration', 'test_unit:integration' or 'migration' Run rails generate --help for more options. how to get this migration succesfull? |
Filterrific Not Passing Multiple Parameters to Scope Posted: 15 Nov 2016 06:49 AM PST I have a filterrific scope that accepts multiple parameters. The scope appears to be functioning correctly (I can call Marketplace::Lot.with_price({}) in the console and it returns the correct results), but filterrific isn't passing any data to it when I enter information on the form. Here is my filterrific declaration in the model filterrific( default_filter_params: { sorted_by: 'time_remaining_asc' }, available_filters: [ :with_price, :sorted_by, :lots_with_item_type, :search_query ] ) Here is what my controller looks like: @filterrific = initialize_filterrific( Marketplace::Lot, params[:filterrific], select_options: { sorted_by: Marketplace::Lot.options_for_sorted_by, item_types: Marketplace::Lot.options_for_item_types }, persistence_id: 'marketplace_key', ) or return @lots = @filterrific.find.paginate(page: params[:page], per_page: 20) and my view <%= f.fields_for :with_price, OpenStruct.new(@filterrific.with_price) do |with_price_fields| %> <div class="marketseach__shards shards"> <%= with_price_fields.text_field :shards_min, class: 'marketplace__value input', placeholder: 'Low Value' %> - <%= with_price_fields.text_field :shards_max, class: 'marketplace__value input', placeholder: 'High Value' %> </div> <span class="marketsearch__text">or</span> <div class="marketsearch__gems gems"> <%= with_price_fields.text_field :gems_min, class: 'marketplace__value input', placeholder: 'Low Value' %> - <%= with_price_fields.text_field :gems_max, class: 'marketplace__value input', placeholder: 'High Value' %> </div> <% end %> When I submit the form, the price fields appear in the params hash "filterrific"=> { "search_query"=>"Programming", "lots_with_item_type"=>"", "with_price"=>{"shards_min"=>"200", "shards_max"=>"", "gems_min"=>"", "gems_max"=>""}, "sorted_by"=>"alpha_asc" }, However, it never gets to the scope (I have a binding.pry in the scope that never gets hit). I should note that all other scopes are working correctly. I'm sure I'm missing something obvious but I can't find it for the life of me. |
Ruby on Rails - contact form is not working Posted: 15 Nov 2016 06:51 AM PST I followed this website to do the contact form in my rails application. I am using a blank bootstrap template inside the rails application. https://rubyonrailshelp.wordpress.com/2014/01/08/rails-4-simple-form-and-mail-form-to-make-contact-form/ The only difference that I made is that in the contact.rb I added my email class Contact < MailForm::Base attribute :name, :validate => true attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w] {2,})\z/i attribute :message attribute :nickname, :captcha => true def headers { :subject => "My Contact Form", :to => "here I added my email", :from => %("#{name}" <#{email}>) } end end When I run the local host, everything seems to work, even the message appears and it says that the email has been sent. However, when I check my email I don't find anything in the inbox. |
Range exclusive of boundaries in ruby Posted: 15 Nov 2016 07:00 AM PST I have a range array like: range_array = [4830..5520, 2000..2700, 600..1335, 3660..4170] And I check for range like: range_array.map{|a| a.include?(3660)}.any? # Gives true as the boundary matches 3660. I want to check for range excluding boundaries. I tried between? , but the problem is same. How do I achieve it with less code? |
TypeError: Cannot read property 'showModal' of undefined (Rails 4 and AngularJS 1.5.8) Posted: 15 Nov 2016 07:20 AM PST I'm trying to display a modal on one of my pages using the "angular-modal-service" but I'm getting the error, TypeError: Cannot read property 'showModal' of undefined when my showAModal(); function is clicked. More about the service I'm using below: https://github.com/dwmkerr/angular-modal-service After looking at some similar issues, it looks like it could be a dependency injection issue, but I can't nail down what I'm doing wrong. I've integrated Angular into my Rails app, and every other service I have used has seemed to work with the implementation below (I am using Angular 1.5.8) javascripts/angular/application.js: (function() { function config($httpProvider, $locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); // Send CSRF token with every http request $httpProvider.defaults.headers.common["X-CSRF-Token"] = $("meta[name=csrf-token]").attr("content"); } angular .module('atmosphere', ['seekBar', 'perfect_scrollbar', 'SongPlayer', 'timecode', 'PlayerBarCtrl', 'SongSearchCtrl', 'GenreSongsCtrl', 'AtmoDashboardCtrl', 'AtmoChatCtrl', 'PostsCtrl', 'SongsCtrl', 'ProfileCtrl', 'AlbumCtrl', 'ModalCtrl', 'AlbumSongsCtrl', 'MiniLibraryCtrl', 'MaxLibraryCtrl', 'PlaylistCtrl', 'PlayerCtrl', 'ngResource', 'restangular', 'angularSoundManager', 'angularModalService']) .config(config); })(); MaxLibraryCtrl.js (removed controlled code that wasn't pertinent): (function (){ function MaxLibraryCtrl($scope, $resource, $interval, Restangular, angularSoundManager, ModalService) { $scope.showAModal = function() { // Just provide a template url, a controller and call 'showModal'. ModalService.showModal({ templateUrl: '/templates/testing_modal.html', controller: "ModalCtrl" }).then(function(modal) { // The modal object has the element built, if this is a bootstrap modal // you can call 'modal' to show it, if it's a custom modal just show or hide // it as you need to. modal.element.modal(); modal.close.then(function(result) { $scope.message = result ? "You said Yes" : "You said No"; }); }); }; } angular .module('MaxLibraryCtrl', ['angularSoundManager', 'angularModalService']) .controller('MaxLibraryCtrl', ['$scope', '$resource', '$interval', 'Restangular', 'ModalService', MaxLibraryCtrl]); })(); libraries/show.html.erb: <h1>Your Library</h1> <div ng-controller="MaxLibraryCtrl"> <button ng-click="showAModal();">Show Modal</button> </div> ModalCtrl.js: (function (){ function ModalCtrl($scope) { $scope.hello = "Hi!"; } angular .module('ModalCtrl', []) .controller('ModalCtrl', ['$scope', ModalCtrl]); })(); public/templates/testing_modal.html: <h1>Hello!</h1> <div ng-controller="ModalCtrl"> <p>{{ hello }}</p> </div> Bowerfile: asset "angular" asset "angular-pusher" asset "lodash" asset "restangular" asset "buzz" asset "raphael" asset "morris" asset "angular-soundmanager2" asset "angular-modal-service" asset "eve" asset "angular-perfect-scrollbar" asset "perfect-scrollbar" application.js: // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require wiselinks //= require angular //= require angular-pusher //= require lodash //= require restangular //= require buzz //= require braintree //= require raphael //= require morris //= require angular-soundmanager2 //= require angular-modal-service //= require eve //= require angular-perfect-scrollbar //= require perfect-scrollbar // //= require_tree . Thanks in advance for any help on this! UPDATE: When removing all other dependencies from the MaxLibraryCtrl, so that it looks like the following, the error disappears, and the correct information is displayed, but it is not in a Modal. The information just displays on the page. Thoughts? (function (){ function MaxLibraryCtrl($scope, ModalService) { $scope.showAModal = function() { // Just provide a template url, a controller and call 'showModal'. ModalService.showModal({ templateUrl: '/templates/testing_modal.html', controller: "ModalCtrl" }).then(function(modal) { // The modal object has the element built, if this is a bootstrap modal // you can call 'modal' to show it, if it's a custom modal just show or hide // it as you need to. modal.element.modal(); modal.close.then(function(result) { $scope.message = result ? "You said Yes" : "You said No"; }); }); }; } angular .module('MaxLibraryCtrl', ['angularModalService']) .controller('MaxLibraryCtrl', ['$scope', 'ModalService', MaxLibraryCtrl]); })(); |
Handling Non Logged In user - Rails 4 - Devise Posted: 15 Nov 2016 06:45 AM PST I have an agent model and an agent_review model. I have some controller logic that will save an agent's ID when that user is logged in. However, when a non-logged in user tries to leave a review I get a NoMethodError: undefined method id for nil:NilClass . I have tried rescue and couldn't manage to get that to work. The hope is to be able to have the non-logged in agent_id return nil and then any agent with an ID of Nil default to Guest in the view. Unless there is a better way to accomplish this goal. agent_reviews_controller: def create @agent_review = AgentReview.new(agent_review_params) @agent_review.reviewer_id = current_agent.id respond_to do |format| if @agent_review.save AgentReviewMailer.agent_review_message(@agent_review, @agent).deliver_later format.html { redirect_to agent_agent_reviews_path, notice: 'Agent review was successfully created.' } format.json { render :show, status: :created, location: @agent_agent_review } else format.html { render :new } format.json { render json: @agent_review.errors, status: :unprocessable_entity } end end end index.html.erb: <div class="container feedback-index"> <% @agent_reviews.each do |agent_review| %> <div class="row feedback-strip"> <p>Submitted: <%= agent_review.created_at.strftime('%D @ %I:%M %p') %></p> <p>Name: <%= agent_review.reviewer.name %></p> <p class="star-rating" data-score= <%= agent_review.rating %> >Rating: </p> <p>Review: <%= agent_review.comment %></p> </div><br> <% end %> </div> |
administrate ruby gem: customizing the resource name in the index vs show pages Posted: 15 Nov 2016 06:35 AM PST By overriding the display_resource() method in an administrate dashboard, it is possible to customize what gets shown in both the index and collection pages (see this). But in many cases, one would like to see a shorter version of the resource name in a table column, than at the top of a "show" page. For example, initials vs. full name. How would you accomplish that with this gem? |
Rails 5 rename CRUD route Posted: 15 Nov 2016 06:42 AM PST I have the following Rails 5 resources, and I want the URL to show /welcome on huddles#index (as well as for the huddles_path url helper). e.g, I don't want huddles_welcome_path . Can this be done? Thank you! resources :huddles do get '/welcome', to: 'huddles#index' resources :invitations end |
How to use Kaminari Pagination for api search Results Posted: 15 Nov 2016 06:25 AM PST I am using the gem kaminari. There as syntax is stated for the controller: @search_web = Search.results_web(params[:search_web]).page(params[:page]).per(10) Search.results_web(params[:search_web]) is giving me 50 results of my Api search and with the .page(params[:page]).per(10) ist should show only 10 plus pagination But when I put my code in the view: This error is showing up. undefined method `total_pages' for nil:NilClass Any idea where and how to define 'total_pages' |
Getting this rails error: ActionController::ParameterMissing in PostsController#new Posted: 15 Nov 2016 06:20 AM PST Error: ActionController::ParameterMissing in PostsController#new param is missing or the value is empty: post I'm working on a 2 model rails app and when I try to go to the "new post" link to create a post this error comes up. BUT none of my actual code is highlighted...a blank line is highlighted above my "private, def post-params" code. def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path end error code highlights here private def post_params params.require(:post).permit(:name, :photo_url, :description, :resume) end form.html.erb <%= form_for :post, url: posts_path(@post), method: :post do |f| %> <p><%= f.label :name %><br> <%= f.text_field :name %> </p> <p> <%= f.label :photo_url %><br> <%= f.text_area :photo_url %> </p> <p> <%= f.label :description %><br> <%= f.text_area :description %></p> <p> <%= f.label :resume %><br> <%= f.text_area :resume %> </p> <p> <%= f.submit %> </p> <% end %> I have all of the correct params from my schema listed, so I think it might have to do with syntax or my path? Nothing I've changed in syntax or path naming has worked so far. |
Linking members through referrals - Rails Posted: 15 Nov 2016 06:54 AM PST I have used Devise to create a referral tracking system similar to this article. I have added 2 columns to the Members table: refer:string and referral_code:string . When a user registers a unique string is created for them and saved in refer to be used later as their referral code, when they register and are using a referral link, the referer's refer code gets saved to the refered member's referral_code field. The problem that I have is linking the referer and referral_code, so that the person that referred can see a list of all the members that signed up with their referral_code. I need assistance with the query that I can run to link the 2. Any assistance will be greatly appreciated. |
Rails console throwing error for ActiveRecord::Base.connection.table_structure("<table name>") Posted: 15 Nov 2016 06:01 AM PST I am trying to access table structure through the following command: ActiveRecord::Base.connection.table_structure("projects") The console throws the following error: NoMethodError: protected method `table_structure' called for # < ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x6559050> I wanted to know how the Rails console work and what is the reason behind this error? Is there any way I can access table structure through Rails console, instead of switching to Sqlite3 frequently to check the schema? |
Stub Net::HTTPCreated response in rspec Posted: 15 Nov 2016 05:51 AM PST I am a uploading image file on another site, and they have provided upload API for the same. File upload process is divided into 2 parts - Create image Id (POST)
- Upload image (PUT)
When I create an image id, it returns id in the response. For this, I have added following methods that achieves this functionality. def create_image_id response = create_via_api(data) # we get response in the following format # #<Net::HTTPCreated 201 Created readbody=true> find_id_from_response(response) end def create_via_api(data) access_token.post(IMAGE_CREATE_URL, data, 'Accept' => ACCEPT_HEADER) end # We are getting id from the response headers in the following format # location: SITE_URL/imageResources/5ac2acb2 def find_id_from_response(response) id = response.to_hash['location'].first return unless id id.split('/').last.chomp end Now I have to write the test case for the create_image_id method. As for test case communicate with 3rd party API is not a good practice. So I am stubbing the POST response say, allow(Image).to receive(:find_id_from_response).and_return('1234') so it will always return id as 123 so that I can write test case as expect(image. create_image_id).to eq 1234 As you can see find_id_from_response take parameter (#). Note: here is the header of the response [36] pry(#)> response.to_hash { "content-type"=>["text/plain"], "x-frame-options"=>["SAMEORIGIN"], "location"=>["www.example.com/imageResources/cd87b8ef"], "vary"=>["Accept-Encoding"], "cache-control"=>["max-age=0, no-cache"], "pragma"=>["no-cache"], "date"=>["Tue, 15 Nov 2016 12:01:56 GMT"], "connection"=>["close"] } I tried with following [28] pry()> Net::HTTPCreated.new(1, 201, 'Created') => #<Net::HTTPCreated 201 Created readbody=false> [29] pry()> a = Net::HTTPCreated.new(1, 201, 'Created') => #<Net::HTTPCreated 201 Created readbody=false> [30] pry()>)> a.to_hash => {} it is returning empty hash. So how can I stub the response of create_via_api? Let me know anything you need. |
ExtJS: Unable to logout using rails as backend Posted: 15 Nov 2016 06:08 AM PST I have an ExtJS6 app as frontend and rails at backend. Using devise for authentication. sessions#destroy looks like def destroy cookies.delete :auth_token reset_session sign_out(:user) render json: { success: true, message: 'Successfully logged out' } end it does logs user out (seemingly) but refreshing page logs previous user in It seems like cookies are not getting reset |
CentOS *** ERROR: Phusion Passenger doesn't seem to be running Posted: 15 Nov 2016 05:29 AM PST While i'm deploying my rails application through capistrano to my CentOS server all the time i have been receiving this error: *** ERROR: Phusion Passenger doesn't seem to be running. If you are sure that it is running, then the causes of this problem could be one of: - You customized the instance registry directory using Apache's PassengerInstanceRegistryDir option, Nginx's passenger_instance_registry_dir option, or Phusion Passenger Standalone's --instance-registry-dir command line argument. If so, please set the environment variable PASSENGER_INSTANCE_REGISTRY_DIR to that directory and run this command again.
- The instance directory has been removed by an operating system background service. Please set a different instance registry directory using Apache's PassengerInstanceRegistryDir option, Nginx's passenger_instance_registry_dir option, or Phusion Passenger Standalone's --instance-registry-dir command line argument.
On my server i have apache and passenger 5.0.30 Firstly i was looking on others answers here on stack: Link to one of these topics. Unfortunately nothing hasn't helped me. I tried to set the env path and others settings from apache conf as well. Any idea what should i change in order to deploy my rails app? Where is the full path to the first passenger-status in PATH? Does it match passenger_root? Below are my logs: $ passenger-config validate-install > What would you like to validate? Use <space> to select. If the menu > doesn't display correctly, press '!' > > ⬢ Passenger itself ‣ ⬢ Apache > > ------------------------------------------------------------------------- > > Checking whether there are multiple Apache installations... Only a > single installation detected. This is good. > > ------------------------------------------------------------------------- > > * Checking whether this Passenger install is in PATH... ✓ * Checking > whether there are no other Passenger installations... ✓ * Checking > whether Apache is installed... ✓ * Checking whether the Passenger > module is correctly configured in Apache... ✓ > > Everything looks good. :-) $ rvmsudo passenger-memory-stats Version: 5.0.30 Date : 2016-11-15 13:43:44 +0100 ---------- Apache processes ---------- PID PPID VMSize Private Name -------------------------------------- 25188 1 476.6 MB 1.5 MB /usr/sbin/httpd -DFOREGROUND 25220 25188 270.4 MB 0.5 MB /usr/sbin/httpd -DFOREGROUND 25246 25188 478.6 MB 0.2 MB /usr/sbin/httpd -DFOREGROUND 25247 25188 478.6 MB 0.2 MB /usr/sbin/httpd -DFOREGROUND 25248 25188 478.6 MB 0.2 MB /usr/sbin/httpd -DFOREGROUND 25249 25188 478.6 MB 0.2 MB /usr/sbin/httpd -DFOREGROUND 25250 25188 478.6 MB 0.2 MB /usr/sbin/httpd -DFOREGROUND ### Processes: 7 ### Total private dirty RSS: 3.08 MB -------- Nginx processes -------- ### Processes: 0 ### Total private dirty RSS: 0.00 MB ----- Passenger processes ----- PID VMSize Private Name ------------------------------- 25222 421.0 MB 0.9 MB Passenger watchdog 25225 772.6 MB 1.5 MB Passenger core 25234 431.3 MB 1.0 MB Passenger ust-router ### Processes: 3 ### Total private dirty RSS: 3.39 MB My apache config file: <VirtualHost *:80> ServerName www.app.com ServerAdmin admin DocumentRoot "/srv/www/app_name/current/public" LoadModule passenger_module /home/userr/.rvm/gems/ruby-2.2.5/gems/passenger-5.0.30/buildout/apache2/mod_passenger.so #<IfModule mod_passenger.c> # PassengerRuby /usr/local/rvm/gems/ruby-2.2.5 # PassengerRoot /usr/local/rvm/gems/ruby-2.2.5/gems/passenger-5.0.30 # PassengerDefaultRuby /usr/local/rvm/gems/ruby-2.2.5/wrappers/ruby # PassengerInstanceRegistryDir /tmp #</IfModule> <IfModule mod_passenger.c> PassengerRoot /home/userr/.rvm/gems/ruby-2.2.5/gems/passenger-5.0.30 PassengerDefaultRuby /home/userr/.rvm/gems/ruby-2.2.5/wrappers/ruby PassengerInstanceRegistryDir /tmp </IfModule> Options -Indexes -FollowSymLinks -MultiViews LogLevel warn ErrorLog logs/www.app.com-error.log TransferLog logs/www.app.com-access.log CustomLog logs/www.app.cp,.log combined <Directory /srv/www/app_name/current/public> AddDefaultCharset UTF-8 <IfModule mod_authz_core.c> # Apache 2.4 <RequireAny> Require all granted </RequireAny> </IfModule> <IfModule !mod_authz_core.c> # Apache 2.2 Order Deny,Allow Deny from All Allow from All </IfModule> </Directory> </VirtualHost> And my env path: env file: SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin LOGNAME=root USER=root USERNAME=root HOME=/root SUDO_COMMAND=/bin/env PASSENGER_INSTANCE_REGISTRY_DIR=/tmp SUDO_USER=userr SUDO_UID=1001 SUDO_GID=100 PASSENGER_INSTANCE_REGISTRY_DIR=/tmp For shore i'm making something wrong. Thanks for every advice. |
Trying to configure UberRUSH Javascript Module Posted: 15 Nov 2016 05:48 AM PST I want to utilize the UserRUSH API that can be found on this link: UBERRUSH Javascript API So basically I tried integrating this package by calling npm install uber-rush This created a node_modules folder and the configuration for application.rb is require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) module Workspace class Application < Rails::Application config.active_record.raise_in_transactional_callbacks = true config.assets.paths << Rails.root.join('node_modules') end end I created a file named donation.js and tried utilizing the UberRUSH module yet I get an error, is there something I have to do to the application.js file to fully configure the node module in Rails? |
Minitest Reporters Gem doesn't show console colors Posted: 15 Nov 2016 05:20 AM PST I've just installed a gem called minitest-reporters. When I run the command rails test , the gem works fine, but it doesn't give me the console colors that lets me know red is for failing test and green for passing test. I'm using the cmd prompt that comes with Windows, and when I run the command rails test , this is whats in my terminal: C:\User\AB\Desktop\test_app>>rails test ansi: 'gem install win32console' to use color on Windows Started with run options --seed 9998 /0: [=--=---=---=---=---=---=---=---=---=-] 0% Time: 00:00:00, 5/1: [======= ] 20% Time: 00:00:02, 5/2: [============== ] 40% Time: 00:00:02, 5/3: [===================== ] 60% Time: 00:00:02, 5/4: [============================ ] 80% Time: 00:00:02, 5/5: [===================================] 100% Time: 00:00:02, Time: 00:00:02 Finished in 2.64782s 5 tests, 9 assertions, 0 failures, 0 errors, 0 skips How can I get the console colors to work on a Windows cmd prompt for testing? |
Rails error - ActionController::UrlGenerationError in BookingsController#create Posted: 15 Nov 2016 05:44 AM PST I have the above error on my Events app I'm building using Rails. The error relates to the 'show' action in the bookings_controller as clarified here - 'No route matches {:action=>"show", :controller=>"bookings" ' - on the error message. The booking system aims to cater for both free and paid bookings. The free bookings routes go to the show page as required. The above error happens when making a paid booking (payments via Stripe). This is the relevant controller code - bookings_controller.rb def new @event = Event.find(params[:event_id]) @booking = @event.bookings.new(quantity: params[:quantity]) # which person is booking the event? @booking.user = current_user end def create @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) @booking.user = current_user if @booking.paid_booking flash[:success] = "Your place on our event has been booked" @booking.update_attributes!(booking_number: "MAMA" + '- ' + SecureRandom.hex(4).upcase) redirect_to event_booking_path(@event) else flash[:error] = "Booking unsuccessful" render "new" end end def free_booking if @booking.free_booking @booking.update_attributes!(booking_number: "MAMA" + '- ' + SecureRandom.hex(4).upcase) redirect_to event_booking_path(@event) else flash[:error] = "Booking unsuccessful" render "new" end end def show @event = Event.find(params[:event_id]) @booking = @event.bookings.new @booking = Booking.find_by(params[:booking_number]) end def update puts params @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) if @booking.save redirect_to event_booking_path , notice: "Booking was successfully updated!" else render 'new' end end private def booking_params params.require(:booking).permit(:stripe_token, :booking_number, :quantity, :event_id, :stripe_charge_id, :total_amount) end The error message focuses on this line in the @booking.paid_booking method - redirect_to event_booking_path(@event) This is odd as its the same route used for free_booking which routes through to the show page with no errors. This is my view forms for free & paid bookings - <% if @booking.free_booking %> <div class="col-md-6 col-md-offset-3" id="eventshow"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading"> <h2>Confirm Your Booking</h2> </div> <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %> <% if @booking.errors.any? %> <h2><%= pluralize(@booking.errors.count, "error") %> prevented this Booking from saving:</h2> <ul> <% @booking.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> <% end %> <div class="form-group"> <p>Please confirm the number of spaces you wish to reserve for this event.</p> <%= form.input :quantity, class: "form-control" %> </div> <p> This is a free event. No payment is required.</p> <div class="panel-footer"> <%= form.submit :submit, label: 'Confirm Booking', class: "btn btn-primary" %> <% end %> </div> <% else %> <div class="col-md-6 col-md-offset-3" id="eventshow"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading"> <h2>Confirm Your Booking</h2> </div> <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %> <div class="calculate-total"> <p> Confirm number of spaces you wish to book here: <input type="number" placeholder="1" name="booking[quantity]" min="1" value="1" class="num-spaces"> </p> <p> Total Amount £<span class="total" data-unit-cost="<%= @event.price %>">0</span> </p> </div> <span class="payment-errors"></span> <div class="form-row"> <label> <span>Card Number</span> <input type="text" size="20" data-stripe="number"/> </label> </div> <div class="form-row"> <label> <span>CVC</span> <input type="text" size="4" data-stripe="cvc"/> </label> </div> <div class="form-row"> <label> <span>Expiration (MM/YYYY)</span> <input type="text" size="2" data-stripe="exp-month"/> </label> <span> / </span> <input type="text" size="4" data-stripe="exp-year"/> </div> </div> <div class="panel-footer"> <%= form.button :submit %> </div> <% end %> <% end %> </div> </div> </div> This is the routes file - routes.rb Rails.application.routes.draw do devise_for :users, :controllers => { omniauth_callbacks: "omniauth_callbacks", registrations: "registrations" } resources :users # the above resource draws out routes for user profiles resources :events do resources :comments resources :bookings end root 'events#index' end And routes - I'm sure this is something quite obvious put I'm afraid I can't spot it. |
Build vanity urls with variables stored in a different table from the model Posted: 15 Nov 2016 05:16 AM PST I am trying to build vanity urls with FriendlyId gem for a specific model Teacher to display www.mysite.com/teachers/{first_name}-{last_name} instead of wwww.mysite.com/teachers/{id} The problem that I encounter is that the information on the {first_name} / {last_name} is stored in the table Contact accessible through User and not in Teacher's one. The relation between the tables is as follows: - Teacher belongs_to :user - User has_one :contact I added in my Teacher model: extend FriendlyId friendly_id :full_name_to_url, use: :slugged So FriendlyId calls the method full_name_to_url to create the slug: def full_name_to_url "#{self.user.contact.first_name.downcase.gsub(" ","-")}-#{self.user.contact.last_name.downcase.gsub(" ","-")}" end I received the following message when trying to apply and save all the changes to the already existing records: Teacher.find_each(&:save) NoMethodError: undefined method `contact' for nil:NilClass I guess there is something wrong with my method? |
Sendgrid not sending emails Posted: 15 Nov 2016 05:07 AM PST i added sendgrid to my app on heroku as my email sender, but each time user trys to signup,the error occurs with the text "www.mydomain.com" is currently unable to handle this request", heroku logs does not show any error. here is my production.rb config.action_mailer.smtp_settings = { :address => "smtp.sendgrid.net", :port => "587", :authentication => :plain, :user_name => "<%= ENV['SENDGRID_USERNAME'] %>", :password => "<%= ENV['SENDGRID_PASSWORD'] %>", :domain => "mydomain.com", :enable_starttls_auto => true } |
Retrieving data from two Rails model Posted: 15 Nov 2016 05:26 AM PST I have an Activation model that belongs to User. I'm trying to display information of the activation that the user has submitted in the views, but I'm not sure how to do this. For example, class Activation < ApplicationRecord belongs_to :user default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :dealer_store, presence: true, length: { maximum: 50 } validates :customer_name, presence: true, length: { maximum: 50 } validates :customer_phone_number, presence: false, length: { maximum: 10 } class User < ApplicationRecord has_many :activations validates :name, presence: true, length: { maximum: 50 } I am able to get data from the user of the activations with the user id like so <%= activation.user.dealer_store %> How would I obtain the customer_phone_number of the activation of the user? I seem to be missing something You may find it here https://bitbucket.org/QuriouslyStrong/sample_app |
"Stack level too deep" when we try to access deleted object Posted: 15 Nov 2016 05:34 AM PST Current env: Rails 4.2 Ruby 2.1.4 DB: mongodb 4 My current project is a multi-tenant architecture and hence all models defined :belongs_to a main object lets say "account". Whenever I delete any child model(say "library"), if I try to access(either delete/show operation) it immediately, I am getting the below exception consistently: Stack level too deep with exception raised => actionpack (4.2.0) lib/action_dispatch/middleware/reloader.rb:79 Basically here is model structure: class Account . . has_many :libraries, dependent: :delete end class Library . . belongs_to :account end Using mongoid as DB. Any suggestions are Note: all models are fetched using "account_id" relation along with the object id. Also once i kill the serve and restart it, i am getting the proper "Document not found" for the deleted object. EDIT: Delete operation: def destroy_library self.destroy end Tried removing "dependent: delete" as suggested by other threads but no luck. |
How to use turnjs in Rails? Posted: 15 Nov 2016 06:27 AM PST i am working on a Rails Project and i have to implement turn.js in it. I have used it earlier in a Non-Rails project, but now the problem is i don't have any idea how to use the same in a Rails project, i have searched on internet and found the following gem: https://bitbucket.org/appfellas/turnjs-rails but they don't have mentioned how to use it, it only includes the js file and some libraries. Please if anybody knows how to use it then let me know. If you have any working example then please share it. Thanks. |
403 Forbidden Error for accessing images on google cloud bucket after transferred from one bucket to another Posted: 15 Nov 2016 04:08 AM PST Actually I am using google cloud bucket for image upload in my rails app. I am using paper clip for image upload. I have used bucket name "abcd-old". I uploaded some of the images through app. It was working fine. But as of now I transffered the content of "abcd-old" bucket to new bucket "abcd-new". Also set the same permission as it was for old one. But now images are broken in the app. it shows "403 forbidden error". If I upload new image that will work. But old I mean transffered images are broken. Please help me on this. This is the error I am getting <Error> <Code>AccessDenied</Code> <Message>Access denied.</Message> <Details> Anonymous users does not have storage.objects.list access to bucket artrium-media-staging. </Details> </Error> |
Why elastic search is not indexing the association Posted: 15 Nov 2016 05:48 AM PST class Doctor < ActiveRecord::Base has_many :doctors_doctor_branches, foreign_key: "doctor_id", dependent: :destroy has_many :doctor_branches, through: :doctors_doctor_branches def as_indexed_json(options={}) as_json( include: { doctor_branches: {only: [:id, :name]} } ) end end Relationship between Doctor and DoctorBranch is correct, as Doctor.find(1).doctor_branches gives me AR array. But when I do response = Doctor.__elasticsearch__.search 'Yoga' I am not getting results for response. |
Bitly :ActionView::Template::Error (INVALID_URI - '500') Posted: 15 Nov 2016 05:30 AM PST Bitly is showing error when I tried to show url. I am using bitly gem with version '1.0.2'. reports_controller: def get_bitly_url(url) if Rails.env.development? return url else bitly = Bitly.new('myapp', 'R_e0gs1dra0442a20a85j0d59156e4060o') bitly.shorten(url).short_url end end application_helper: def get_bitly_url(url) if Rails.env.development? return url else bitly = Bitly.new('myapp', 'R_e0gs1dra0442a20a85j0d59156e4060o') bitly.shorten(url).short_url end end _delivery_sidebar.html.erb: <%= f.inputs :id => 'deliver', :class => 'inputs' do %> <%= f.input :link_placeholder, :as => :text, :label => false, :input_html => { :id => 'copy_link', :class => '', :value => "#{get_bitly_url(user_report_url(@user, @report))}", :rows => 2, :cols => 30, :maxlength => 490} %> <% end %> In server, I am getting warnings in server as: [DEPRECATION] The bit.ly version 2 API has been superseded by version 3 and will be removed. See the README for details and in the production log, I am getting: Started GET "/users/2/reports/41/edit" for 127.0.0.1 at 2016-11-15 11:37:31 +0530 Processing by ReportsController#edit as HTML Parameters: {"user_id"=>"2", "id"=>"41"} [1m[36mUser Load (0.4ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL AND `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1 [0m [1m[35mUser Load (2.2ms) [0m SELECT `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL AND `users`.`id` = 2 LIMIT 1 [1m[36mReport Load (0.2ms) [0m [1mSELECT `reports`.* FROM `reports` WHERE `reports`.`deleted_at` IS NULL AND `reports`.`user_id` = 2 AND `reports`.`id` = 41 LIMIT 1 [0m [1m[35m (3.8ms)[0m SELECT COUNT(*) FROM `icons` WHERE `icons`.`report_id` = 41 [1m[36mOauthAccessToken Load (1.6ms) [0m [1mSELECT `oauth_access_tokens`.* FROM `oauth_access_tokens` WHERE `oauth_access_tokens`.`provider` = 'instagram' AND `oauth_access_tokens`.`user_id` = 2 ORDER BY `oauth_access_tokens`.`id` ASC LIMIT 1 [0m [1m[35m (2.5ms)[0m SELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 AND (id IS NOT NULL) Rendered reports/_navigation.html.erb (0.1ms) [1m[36m (0.2ms)[0m [1mSELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 AND (photo_type = 0) [0m Rendered reports/_photos.html.erb (0.7ms) [1m[35mPhoto Load (3.8ms) [0m SELECT `photos`.* FROM `photos` WHERE `photos`.`report_id` = 41 AND (id IS NOT NULL AND photo_type = 1) Rendered reports/_photos_inline_js.html.erb (6.3ms) [1m[36m (0.9ms)[0m [1mSELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 [0m [1m[35mCACHE (0.0ms) [0m SELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 AND (photo_type = 0) [["report_id", 41]] [1m[36mIcon Load (7.6ms) [0m [1mSELECT `icons`.* FROM `icons` WHERE `icons`.`report_id` = 41 AND (id IS NOT NULL) ORDER BY position_id ASC [0m [1m[35mCACHE (0.0ms) [0m SELECT COUNT(*) FROM `icons` WHERE `icons`.`report_id` = 41 [["report_id", 41]] [1m[36mIcon Load (0.2ms)[0m [1mSELECT `icons`.* FROM `icons` WHERE `icons`.`report_id` = 41 ORDER BY position_id ASC [0m Rendered reports/_main_icon.html.erb (0.8ms) Rendered reports/_main_icon.html.erb (0.1ms) Rendered reports/_main_icon.html.erb (0.0ms) [1m[35mCACHE (0.0ms) [0m SELECT COUNT(*) FROM `icons` WHERE `icons`.`report_id` = 41 [["report_id", 41]] [1m[36mCACHE (0.0ms)[0m [1mSELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 [0m [["report_id", 41]] [1m[35mCACHE (0.0ms) [0m SELECT COUNT(*) FROM `photos` WHERE `photos`.`report_id` = 41 [["report_id", 41]] Rendered reports/_icons.html.erb (13.3ms) Rendered users/_image.html.erb (0.6ms) Rendered users/_logo.html.erb (0.5ms) Rendered reports/sidebars/_choose_sidebar.html.erb (1.1ms) Rendered reports/sidebars/_create_sidebar.html.erb (0.6ms) Rendered reports/sidebars/_create_sidebar_photos.html.erb (0.4ms) Rendered reports/sidebars/_design_sidebar.html.erb (0.2ms) Rendered reports/sidebars/_delivery_sidebar.html.erb (1320.6ms) Rendered reports/_creation.html.erb (1405.2ms) Rendered reports/edit.html.erb within layouts/report (1407.7ms) Completed 500 Internal Server Error in 1477ms (ActiveRecord: 23.4ms) ActionView::Template::Error (INVALID_URI - '500'): 46: </div> --> 47: <div id="link-it-content"> 48: <% if params[:action] == 'edit' %> 49: <ul><%= f.input :link_placeholder, :as => :text, :label => false, :input_html => { :id => 'copy_link', :class => '', :value => "#{get_bitly_url(user_report_url(@user, @report))}", :rows => 2, :cols => 30, :maxlength => 490} %></ul> 50: <% else %> 51: <ul><%= f.input :link_placeholder, :as => :text, :label => false, :input_html => { :id => 'copy_link', :class => '', :value => "Please add a title to your #{Rails.application.config.custom.report_name}.", :rows => 2, :cols => 30, :maxlength => 490} %></ul> 52: <% end %> app/helpers/application_helper.rb:50:in `get_bitly_url' app/views/reports/sidebars/_delivery_sidebar.html.erb:49:in `block in _app_views_reports_sidebars__delivery_sidebar_html_erb__1024322237189702065_80604080' app/views/reports/sidebars/_delivery_sidebar.html.erb:30:in `_app_views_reports_sidebars__delivery_sidebar_html_erb__1024322237189702065_80604080' app/views/reports/_creation.html.erb:533:in `block (2 levels) in _app_views_reports__creation_html_erb___444881577336758328_39480120' app/views/reports/_creation.html.erb:311:in `block in _app_views_reports__creation_html_erb___444881577336758328_39480120' app/views/reports/_creation.html.erb:292:in `_app_views_reports__creation_html_erb___444881577336758328_39480120' app/views/reports/edit.html.erb:5:in `_app_views_reports_edit_html_erb__701035442935272720_31605780' How to come out of this error? |
google analytics embed api with turbolinks in rails Posted: 15 Nov 2016 05:02 AM PST I am trying to implement the google analytics embed api using javascript code provided by google to my rails app and taking help from this link -> https://ga-dev-tools.appspot.com/embed-api/. Now I dont know how to run these scripts on every page change because these javascripts listens to the page load event and rails uses turbolinks that actually doesn't loads the page it swaps only body and title. Now the problem is that javascript doesn't respond as it does not know that page has been changed. Please help me out. <script> (function (w, d, s, g, js, fs) { g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } }; js = d.createElement(s); fs = d.getElementsByTagName(s)[0]; js.src = 'https://apis.google.com/js/platform.js'; fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); }; }(window, document, 'script')); </script> <div id="embed-api-auth-container"></div> <div id="chart-container"></div> <div id="view-selector-container"></div> <script> gapi.analytics.ready(function () { /** * Authorize the user immediately if the user has already granted access. * If no access has been created, render an authorize button inside the * element with the ID "embed-api-auth-container". */ gapi.analytics.auth.authorize({ container: 'embed-api-auth-container', clientid: '7xxxxxxxxxx-mtgoounogp8pu2brjsi1mfpbrohtcppd.apps.googleusercontent.com' }); /** * Create a new ViewSelector instance to be rendered inside of an * element with the id "view-selector-container". */ var viewSelector = new gapi.analytics.ViewSelector({ container: 'view-selector-container' }); // Render the view selector to the page. viewSelector.execute(); /** * Create a new DataChart instance with the given query parameters * and Google chart options. It will be rendered inside an element * with the id "chart-container". */ var dataChart = new gapi.analytics.googleCharts.DataChart({ reportType: 'ga', query: { metrics: 'ga:sessions', dimensions: 'ga:date', 'start-date': '30daysAgo', 'end-date': 'yesterday' }, chart: { container: 'chart-container', type: 'LINE', options: { width: '100%' } } }); /** * Render the dataChart on the page whenever a new view is selected. */ viewSelector.on('change', function (ids) { dataChart.set({ query: { ids: ids } }).execute(); }); }); </script> for the very first time my code is running properly but if i switch to another link or come back to the same page after visiting another page via turbolinks the javascript doesn't run. Please help. Thanks |
No comments:
Post a Comment