My form_for [post, comment] is submitting to the wrong url? Posted: 26 Aug 2016 07:44 AM PDT I have a form_for in my application that is submitting to the wrong url. <% @posts.each do |post| %> <form class="col-md-12"> <% comment = post.comments.build %> <%= form_for [post, comment], :url => post_comments_path(post), html: {class: "col-md-12", method: "POST"} do |comment_fields| %> <div class="form-group"> <%= comment_fields.text_area :content, placeholder: "Write a comment...", class: "form-control", rows: "4" %> </div> <div class="form-group"> <a class="col-md-1" href="#">Cancel</a> <%= comment_fields.submit "Comment", class: "col-md-3 pull-right btn btn-primary" %> </div> <% end %> <% end %> Here are is my PostsController index method: def index @user = User.find(params[:user_id]) @posts = @user.posts end I am expecting it to go to POST /posts/:post_id/comments(.:format) comments#create but it is sending this request instead: Started GET "/users/6/posts?utf8=%E2%9C%93&authenticity_token=WgbO5FhAA0ZhXFdk%2FizEbqTVxg2HW9VDY7aUKQTLmy3qLXLC8EH9%2FKr0w53TcId2KYoJmU7uodCFJOIDufno8g%3D%3D&comment%5Bcontent%5D=qqqqqqqqqqqq111&commit=Comment" Here are my routes: Prefix Verb URI Pattern Controller#Action logout GET /logout(.:format) sessions#destroy login GET /login(.:format) sessions#new session POST /session(.:format) sessions#create new_session GET /session/new(.:format) sessions#new edit_session GET /session/edit(.:format) sessions#edit GET /session(.:format) sessions#show PATCH /session(.:format) sessions#update PUT /session(.:format) sessions#update DELETE /session(.:format) sessions#destroy post_likes GET /posts/:post_id/likes(.:format) likes#index POST /posts/:post_id/likes(.:format) likes#create new_post_like GET /posts/:post_id/likes/new(.:format) likes#new edit_like GET /likes/:id/edit(.:format) likes#edit like GET /likes/:id(.:format) likes#show PATCH /likes/:id(.:format) likes#update PUT /likes/:id(.:format) likes#update DELETE /likes/:id(.:format) likes#destroy post_comments GET /posts/:post_id/comments(.:format) comments#index POST /posts/:post_id/comments(.:format) comments#create new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new edit_comment GET /comments/:id/edit(.:format) comments#edit comment GET /comments/:id(.:format) comments#show PATCH /comments/:id(.:format) comments#update PUT /comments/:id(.:format) comments#update DELETE /comments/:id(.:format) comments#destroy user_posts GET /users/:user_id/posts(.:format) posts#index POST /users/:user_id/posts(.:format) posts#create Is there a way to do this with form_for? I could use a form_tag post_likes_path, with a method: delete option, but I want to automatically set the @comment.post_id to the post. |
I'm building a website with rubyonrails and the destroy function is not working instead it is invoking the show method Posted: 26 Aug 2016 07:33 AM PDT This is the destroy function def destroy @restaurant.destroy respond_to do |format| format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully destroyed.' } format.json { head :no_content } end end |
Error - Subject expected, got String Posted: 26 Aug 2016 07:43 AM PDT I have the following migration: create_table :flows do |t| t.string :name t.belongs_to :subject, index: true t.timestamps end My Schemas: create_table "flows", force: :cascade do |t| t.string "name" t.integer "subject_id" t.index ["subject_id"], name: "index_flows_on_subject_id" end create_table "subjects", force: :cascade do |t| t.string "subject" t.datetime "created_at", null: false end And on my form I have the select html: <%= f.select :subject, Subject.all.collect {|s| [ s.subject, s.id ] }, {prompt: 'Select subject'}, class:"form-control" %> But it shows the error: Subject(#30363600) expected, got String(#16228440) # POST /flows.json def create @flow = Flow.new(flow_params) respond_to do |format| if @flow.save Parameters: {"utf8"=>"✓", "authenticity_token"=>"y3cTmsdqweqioXtsCpSlNtmTonyXev+67emGwqfgvGJK4D3Szt1FbZcxe6M7QU8cLYPEbanmkYngzyDvbFPw==", "flow"=>{"name"=>"Create Project", "subject"=>"11"}, "button"=>""} |
What part of a JWT token is unique to the user and doesn't change? Posted: 26 Aug 2016 07:27 AM PDT I have an API made in Rails where people can only make a request to it, if they send along a JWT token - https://jwt.io. I'm using Rack::Attack to rate limit people based on IP. Now I also want to rate limit people based on the request token they send along. Which of the 3 parts of the JWT token below is unique to that user? Does that part change from time to time? In other words... which part can I identify the user on? eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ |
react-rails prerender third party components throwing warnings Posted: 26 Aug 2016 07:26 AM PDT I'm using the following gems: gem 'react-rails' gem 'browserify-rails' I'm trying to use server side rendering with: <%= react_component('Chart', { data: report.entries_data }, { prerender: true }) %> My problem is that when I set prerender to true, all the thirdparty libraries i'm using are throwing a bunch of warnings to the console: Warning: You are manually calling a React.PropTypes validation function for the `type` prop on `ChartistGraph`. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library There's one warning per prop, so there's a lot of warnings being thrown for some components. They happen for example for react-select , react-chartist or react-modal These warnings don't show up if I turn of prerendering. My package.json : "dependencies": { "babel-preset-es2015": "^6.14.0", "babel-preset-react": "^6.11.1", "babelify": "^7.3.0", "bootstrap-select": "^1.11.0", "browserify": "^13.1.0", "browserify-incremental": "^3.1.1", "chartist": "^0.9.8", "react": "^15.3.1", "react-chartist": "^0.10.2", "react-dom": "^15.3.1", "react-modal": "^1.4.0" } What is causing this problem? |
How to add an image to a collection in Rails? Posted: 26 Aug 2016 07:37 AM PDT I am trying add image to collections created by user just like something similar to WWW.UNSPLASH.COM Here are my models: class Image < ApplicationRecord has_attached_file :image, styles: { thumb: "376x", medium: "1176x", large: "1176x600" }, default_url: "/images/:style/missing.png" # , single: "1176" validates_attachment_content_type :image, content_type: /\image\/.*\Z/ belongs_to :user belongs_to :collection end class Collection < ApplicationRecord has_many :collections end I would appreciate your assistance. This is my first question, trying to get used to the environment. please bear with me. However here is my below: class AddCollectionIdToImage < ActiveRecord::Migration[5.0] def change add_reference :images, :collection, foreign_key: true end end so far, user can add and delete images successfully. i can also add and remove collection too. Below is my schema too: ActiveRecord::Schema.define(version: 20160819194520) do create_table "collections", force: :cascade do |t| t.string "title" t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "mages", force: :cascade do |t| t.string "title" t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.integer "user_id" t.integer "collection_id" t.index ["collection_id"], name: "index_mages_on_collection_id" t.index ["user_id"], name: "index_mages_on_user_id" end end so far again, the only way i can add images to my collection is by going to this route /collections/new and fill the form through fields_for.. The challenge is this, i cant think through on how to just click on any image with ADD TO COLLECTION BUTTON . and by cicking on the button, list of user created COLLECTIONS will show up and image can be added to any COLLECTION in the list. I dont know if i still bore you people with my question. If i still dont help you to understand my question, then pls ask me leading questions to what you want me to say. I am new commer. Thanks alot. |
Rakuten API (LinkShare) how to get Products by Category Name with special symbols in it? Posted: 26 Aug 2016 06:57 AM PDT I am using Rakuten LinkShare API in my app and I need to pull some products based on category. So I do ProductSerach API reuqest with 'CategoryName' as a cat parqam. BUT there are some categories which include symbols like & ,- etc. and in this case I get an error about not using those in a query. Is this possible to skip the issue in any way? Thanks |
Capybara: Stubbing No Route Matches Posted: 26 Aug 2016 06:52 AM PDT I have a capybara test that checks for content on a page. I have an img tag thats src calls for a URL that does not exist. When I run the test I receive: Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}" ActionController::RoutingError: No route matches [GET] "/avatars/original/missing.png" I honestly don't care about this request. Is there any way for me stub /avatars/original/missing.png on my Capybara test? |
How can I use firefox on heroku Posted: 26 Aug 2016 07:02 AM PDT I am using watir webdriver and its headless functionality along with firefox browser to goto a website, say www.xyz.com .Click on different buttons and download a pdf.I have achieved this in my local environment.When i push my app to heroku, it asked for buildpacks.I have added buildpacks and they are present in my heroku.I found this by running heroku run bash . Dependencies used are: gem 'watir-webdriver', '~> 0.9.1' gem 'headless', '~> 2.2', '>= 2.2.3' Buildpack of Xvfb Buildpack of firefox Xvfb buildpack is working fine.When running browser = Watir::Browser.new(:firefox, :profile => profile) , I am getting strange errors like Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) or set path for firefox . I have set path for firefox Selenium::WebDriver::Firefox::Binary.path='vendor/firefox/firefox-bin' .I can see the firefox installed in that location in my heroku bash . I am not sure whether this is a heroku problem or buildpack problem.Although the develper of buildpack said he was not able to run his firefox buildpack on heroku but he was able to deploy on Amazon EC2 .Is is possible to install and use firefox with all its functionalities(like opening and closing browser, downloading pdf, opening tabs) on heroku? I am sorry if I am not too clear with my question. Firefox Buildpack. begin ActiveRecord::Base.transaction do download_directory = "#{Rails.root}/tmp/#{dir_name}" Selenium::WebDriver::Firefox::Binary.path='vendor/firefox/firefox-bin' profile = Selenium::WebDriver::Firefox::Profile.new profile['download.prompt_for_download'] = false profile['browser.download.folderList'] = 2 # custom location profile['browser.download.dir'] = download_directory profile['browser.helperApps.neverAsk.saveToDisk'] = "application/pdf" # Disable built-in pdf viewer of Firefox browser profile['pdfjs.disabled'] = true profile['pdfjs.firstRun'] = false headless = Headless.new headless.start browser = Watir::Browser.new(:firefox, :profile => profile) # browser.screenshot.save "pp.png" browser.goto 'xyz.com' browser.window.resize_to(some_x,some_y) browser.text_field(:name => "some_name").set("#{some_data}") browser.text_field(:name => "some_password").set("#{password}") browser.button(:name => "button").click #Pdf gets downloaded in the defined location #some database updations headless.destroy end rescue => r end |
Rails jQuery 'post' problems Posted: 26 Aug 2016 06:54 AM PDT In my project I have a button with approximately such code: <a class="start btn" href=start_process_path(@process.id) id="start"></a> and have a jquery event listener for it: $('.start').click((function(_this) { return function(e) { var params; params = $('form', _this.previewJq).serializeArray(); $.post(e.target.href, params, function(json) { if (json.error) { return alert(json.error); } }); return false; }; })(this)); In my routes file I have such lines: resources :processes do patch 'start', on: :member end The problem is that sometimes when I click that button I reacts with nothing. If I open console in Chrome or look in logs, I can see that it throws 404 error saying that I'm trying to send post request to the page that has this button. When I open sources in Chrome browser and but a breakpoint on a line with a post request, it usually works fine. But once I've managed to caught situation when it sad that e.tagret.href has undefined value (or smth like this). What can be the reason for it to be like this? Why jquery can't get href parameter correctly? Thanx in advance! |
What will be the alternate of win32api for Linux? [duplicate] Posted: 26 Aug 2016 06:44 AM PDT This question already has an answer here: I have a Ruby code for a site response. To check if the site is UP Or Down. But it works only for windows.If i want to use it for Ubuntu what will be the change ? I am trying to run this but win32api line getting an error on Ubuntu. require "net/https" require "uri" require "Win32API" uri = URI.parse("https://address ") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) test = response.body delay = 10 message = "Site is OK" title = "Up" api = Win32API.new('user32', 'MessageBox',['L', 'P', 'P', 'L'],'I') until !test.include? "false" time = Time.now.strftime("%d/%m/%Y %H:%M") puts time puts "Down" response = http.request(request) test = response.body sleep(delay) end api.call(0,message,title,0) until test.include? "false" api.call(0,message,title,0) time = Time.now.strftime("%d/%m/%Y %H:%M") puts time puts "Up" response = http.request(request) test = response.body sleep(delay) end |
GET localhost URL through HTTParty in localhost server, produces Net::ReadTimeout error Posted: 26 Aug 2016 06:44 AM PDT I am testing a scenario and getting this error: Net::ReadTimeout in controller#method-one . I tried three ways Console: (works fine): HTTParty.get("http://localhost:3000/controller/method-two?prams=abc") Single Server running on localhost:3000: (shows error): class Controller < ApplicationController require 'net/http' def method-one abc = params[:abc] res=HTTParty.get("http://localhost:3000/controller/method-two?prams=#{abc}") end end Two Server running on different ports localhost:3001/0: (shows error): both server call each other controller#method just to change port i.e Server on Port 3000 call: HTTParty.get("http://localhost:3001/controller/method-other-server?prams=#{abc}") above Get call the server on port 3001 controller#method-other-server which again call back origin server another method to record response i.e. HTTParty.get("http://localhost:3000/controller/method-two?prams=#{abc}") and origin server running on port 3000 get stuck for while and produces Net::ReadTimeout error on origin server port 3000 you might be wonder why I am using two server for one call. because I read over internet that: Localhost server is single threaded so you can't call a localhost url inside the localhost server. please help me I am stuck being beginner in rails. P.S: I've tested these method independently and works fine. but problem rise when I call url from one controller method to another method through HTTParty |
NoMethodError in Pics#show Posted: 26 Aug 2016 06:45 AM PDT if i acces to http://localhost:3000/pics/9 or any post i get this error Showing c:/Sites/insta/app/views/pics/show.html.haml where line #5 raised: undefined method `email' for nil:NilClass Rails.root: c:/Sites/insta Application Trace | Framework Trace | Full Trace app/views/pics/show.html.haml:5:in `_app_views_pics_show_html_haml__310592347_80083632' show.html.haml %h1= @pic.title %p= @pic.description %p Pic by = @pic.user.email %br = link_to "Back", root_path = link_to "Edit", edit_pic_path = link_to "Delete", pic_path, method: :delete, data: { confirm: "Are you sure?" } shema.rb # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160825161502) do create_table "pics", force: :cascade do |t| t.string "title" t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" end add_index "pics", ["user_id"], name: "index_pics_on_user_id" create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end Where is the problem I have searched for a solution but I did not find anything |
syntax error unexpected keyword_else, expecting > keyword_end Posted: 26 Aug 2016 07:44 AM PDT I have one problem in my code in the ruby language. This code was in c sharp and i am converting the code of C# for Ruby. I am studying Ruby through of tutorialspoint but my code has produced some errors. Anyone can help me? The error are: KnightsTour.rb:57 syntax error, unexpected keyword_else, expecting keyword_end KnightsTour.rb:65 syntax error, unexpected end-of-input, expecting keyword_end class KnightsTour def initialize(numero) @num = numero @numSqr = num*num @table = Array.new(num){Array.new(num)} @dx = [2 , 1 , -1, -2, -2, -1, 1 , 2 ] @dy = [1 , 2 , 2 , 1 , -1, -2, -2, -1] end def isAcceptable(x, y) result = (x >= 0 && x <= num - 1) result = result && (y >= 0 && y <= num - 1) result = result && (table[x, y] == 0) return result end def tryMove(i, x, y) done = ( i > numSqr ) #Verifica a qtd de movimentos k = 0; while !done && k < 8 do u = x + dx.at(k) v = y + dy.at(k) end if isAcceptable u,v table[u , v] = i # ==> tenta outro movimento done = tryMove i + 1 , u , v if !done #sem sucesso . Descarta movimento table[u , v] = 0; end end k = k + 1 #passa ao próximo movimento possível return done end def showTour (x , y) $i = 0 $j = 0 table [x][y] = 1 done = tryMove 2 , x , y if done do for i in 0...num for j in j...num puts (table [i , j] + " ") #$j += 1 end puts("\n") #$i += 1 end else puts ("Não há passeio possível") end end end cavalo = KnightsTour.new("7") cavalo.showTour 0,0 |
Passenger alarms for rails application Posted: 26 Aug 2016 06:34 AM PDT I have a rails application where I am continuously getting 'too many users are trying to acces this site' error. If I am correct then this occurs because of passenger queue getting full. One obvious solution is to optimize the code so that requests don't remain in the queue for far too long. But this will take a lot of time and I don't want to lose any users before I can look at & fix the code. Is there a way to get alert/alarm when passengers passenger_max_request_queue_size reaches some threshold ? Need help as soon as possible guyz. |
Rails Search and add filters to the search - geocoder Posted: 26 Aug 2016 07:45 AM PDT I would like some advices on the way to add a filter , on my search form with geocoder. I got a User model and Animal model (animals got a Type argument) And a join table : Animal_User with Animal_ID / User_ID)
Right now, I can locate Users around a city with the choice of Kilometers around that city.That's working fine. I would like to add the filter on the type of animal, that would be great :) Search would look like this : London > 10KM > Filter on Type : dogs Many thanks in advance if you have a glimpse of an idea on how to do that. You will find the search html and the controller. If you need User Model or Animal model i can post it too ( it's really standard Has_many / has_many though association) search.html.erb <div class="search-bar"> <%= form_tag search_path, :class => "webdesigntuts-workshop", method: :get do %> <%= label :user, "" %> <%= text_field_tag :city, params[:city], placeholder: 'City', :input_html => { :value => 'Paris' } %> <%= label :distance, "" %> <%= text_field_tag :distance, params[:distance], placeholder: 'km', :input_html => { :value => '10' } %> <%= submit_tag "Search" %> <% end %> </div> search controller class SearchsController < ApplicationController def search if params[:city].present? @searchs = User.near(params[:city], params[:distance] || 10).where("id != ?", current_user.id) else @searchs = User.all.where("id != ?", current_user.id) end end end |
Login to external site from Rails Posted: 26 Aug 2016 06:10 AM PDT I would like to login to an external https site, through rails based on user/password credentials saved into a rails database. Something like a single sign on. The external site says that you can post the credentials to their login form by loading the email and password to the form and then press ok. But if I do that, then by viewing the source code of the login form, someone may find out the login credentials. I have looked into Mechanize and loading cookies like here Submitting POST data from the controller in rails to another website and Rails 3 - Log into another site and keep cookie in session but it does not seem right. Is there a way to automatically load the credentials from the controller and post to the external site immediately in order to login to that site? Thank you in advance |
Ruby on Rails update multiple records in a single query Posted: 26 Aug 2016 06:51 AM PDT hi i have a rails app in which i want to create multiple records in the single query this is my code inserts = [] 1000.times do inserts.push "user name" end inserts = inserts.map {|bar| "(#{bar.to_s})"}.join(",") ActiveRecord::Base.connection.execute "INSERT INTO `user_dat`.`user_inserts` (`name`) VALUES #{inserts}" What error i am getting is the error in the mysql syntax INSERT INTO `batch_insert`.`batch_inserts` (`name`) VALUES (user name),(user name),(user name),(user name),(user name),(user name),(user name).... upto 1000 i know i want it like ("user name"), ("user name") but i am not able to achieve it can someone please tell me how can i achieve this format of values |
Delayed Job ActiveRecord::Job Load - run every 5 seconds? Posted: 26 Aug 2016 06:04 AM PDT I have a feeling this is the Rails equivalent of hypochondria... but i took a peek into tail -f logs/development.log and then became kind of hypnotized by the output: Delayed::Backend::ActiveRecord::Job Load (0.8ms) UPDATE "delayed_jobs" SET locked_at = '2016-08-26 12:49:09.594888', locked_by = 'host:ghost pid:4564' WHERE id IN (SELECT "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2016-08-26 12:49:09.594275' AND (locked_at IS NULL OR locked_at < '2016-08-26 08:49:09.594332') OR locked_by = 'host:ghost pid:4564') AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING * Delayed::Backend::ActiveRecord::Job Load (0.5ms) UPDATE "delayed_jobs" SET locked_at = '2016-08-26 12:49:14.651262', locked_by = 'host:ghost pid:4564' WHERE id IN (SELECT "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2016-08-26 12:49:14.650707' AND (locked_at IS NULL OR locked_at < '2016-08-26 08:49:14.650765') OR locked_by = 'host:ghost pid:4564') AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING * Delayed::Backend::ActiveRecord::Job Load (0.5ms) UPDATE "delayed_jobs" SET locked_at = '2016-08-26 12:49:19.716179', locked_by = 'host:ghost pid:4564' WHERE id IN (SELECT "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2016-08-26 12:49:19.715433' AND (locked_at IS NULL OR locked_at < '2016-08-26 08:49:19.715494') OR locked_by = 'host:ghost pid:4564') AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING * This runs... every five seconds. So... err, is that... normal? It's occurred to me that this is the way Delayed Job must work, by checking a job against timestamps and so this is just it doing it's thing, but I've failed to locate decent written evidence to that effect. If so... my second concern is won't this burn money on my Heroku Instance? I'd installed the workless gem in an attempt to mitigate costs - but I'm not seeing any code come in to shut that down... Bug or feature, how do i not bankrupt myself? |
Ruby or Ruby on Rails group_by on dynamically changing parameters Posted: 26 Aug 2016 05:49 AM PDT I want to change group_by parameters based on user input. Example: Data on which i am going to group: result = [{"result_1"=>"01","result_2"=>"August","result_3"=>"2016","result_4"=>264},{"result_1"=>"02","result_2"=>"August","result_3"=>"2016","result_4"=>49},{"result_1"=>"03","result_2"=>"August","result_3"=>"2016","result_4"=>53}] I know how a ruby group_by works with multiple parameters. To group_by on result_1 and result_2.It can be done this way: result.group_by{|h| [h["result_1"],h["result_2"]} Above code groups the data based on result_1 and result_2.Here the parameters are hard_coded. I want group_by based on parameters passed dynamically.As dynamic_parameter = ["result_3","result_4"] I want group_by to be as result.group_by{|h| [h["result_3"],h["result_4"]]} i want to do it as roughly: dynamic_parameters.each do |parameter| result.group_by{|h| [h[parameters]} end or similar to: result.group_by{|h| [h[parameters[0]],h[parameters[1]]} These result_3 and result_4 parameters are based on dynamic_parameter array values. Note: Group_by should vary based on the array elements. |
Error while Installing RMagick gem Posted: 26 Aug 2016 05:37 AM PDT I have first installed ImageMagick using this command - sudo apt-get install imagemagick But when I do bundle install I get this error - Gem::Ext::BuildError: ERROR: Failed to build gem native extension. current directory: /home/aasish/.rvm/gems/ruby-2.3.0@re-management/gems/rmagick-2.15.4/ext/RMagick /home/aasish/.rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20160826-4124-lxm3rv.rb extconf.rb Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError) You have to install development tools first. To see why this extension failed to compile, please check the mkmf.log which can be found here: /home/aasish/.rvm/gems/ruby-2.3.0@re-management/extensions/x86_64-linux/2.3.0/rmagick-2.15.4/mkmf.log extconf failed, exit code 1 I need help with this even I tried changing the version of ImageMacick from 6.7.7 to 7.0.2 I using an Ubuntu 14.04 OS this is the error - You have to install development tools first. from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:587:in `try_cpp' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:1091:in `block in have_header' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:320:in `open' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:320:in `open' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:346:in `postpone' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for' from /home/aasish/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:1090:in `have_header' from extconf.rb:38:in `configure_headers' from extconf.rb:18:in `initialize' from extconf.rb:517:in `new' from extconf.rb:517:in `<main>' |
NoMethodError in Pics#new Posted: 26 Aug 2016 06:21 AM PDT if i acces to http://localhost:3000/pics/new i get this error Showing c:/Sites/insta/app/views/pics/_form.html.haml where line #12 raised: undefined method `image' for #<Pic:0xa2ad520> Trace of template inclusion: app/views/pics/new.html.haml Rails.root: c:/Sites/insta Application Trace | Framework Trace | Full Trace app/views/pics/_form.html.haml:12:in `block in _app_views_pics__form_html_haml___443805693_84818352' app/views/pics/_form.html.haml:1:in `_app_views_pics__form_html_haml___443805693_84818352' app/views/pics/new.html.haml:7:in `_app_views_pics_new_html_haml__186267902_85061856' my _form.html.haml = simple_form_for @pic, html: { multipart: true } do |f| - if @pic.errors.any? #errors %h2 = pluralize(@pic.errors.cont, "error") prevented this Pic from saving %ul - @pic.errors.full_message.each do |msg| %li= msg .form-group = f.input :image, input_html: { class: 'form-control' } .form-group = f.input :title, input_html: { class: 'form-control' } .form-group = f.input :description, input_html: { class: 'form-control' } = f.button :submit, class: "btn btn-info" my new.html.haml .col-md-8.col-md-offset-2 .row .panel.panel-default .panel-heading %h1 Post Pic .panel-body = render 'form' Pic.rb class Pic < ActiveRecord::Base belongs_to :user has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ end |
Unable to install an old version of the gem "rmagick" Posted: 26 Aug 2016 07:27 AM PDT I happen to have a bit old rails project, it's rails 3.2 and ruby 2.2.4. Because of this, installing some gems fails, in particular it's "rmagick -v '2.13.2'". $ gem install rmagick -v '2.13.2' Building native extensions. This could take a while... ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. /home/user123/.rubies/ruby-2.2.4/bin/ruby -r ./siteconf20160826-3014-1j0i394.rb extconf.rb checking for Ruby version >= 1.8.5... yes checking for gcc... yes checking for Magick-config... yes checking for ImageMagick version >= 6.4.9... yes checking for HDRI disabled version of ImageMagick... no Can't install RMagick 2.13.2. RMagick does not work when ImageMagick is configured for High Dynamic Range Images. Don't use the --enable-hdri option when configuring ImageMagick. *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/home/user123/.rubies/ruby-2.2.4/bin/$(RUBY_BASE_NAME) extconf failed, exit code 1 Gem files will remain installed in /home/user123/.gem/ruby/2.2.4/gems/rmagick-2.13.2 for inspection. Results logged to /home/user123/.gem/ruby/2.2.4/extensions/x86_64-linux/2.2.0-static/rmagick-2.13.2/gem_make.out I've tried unistalling the library "ImageMagick" and installing one with no hdri, but even that failed because there're other libraries which depend on "ImageMagick" with hdri, thus I haven't been able to reinstall it. And in general, reinstalling a library only for a single rails project doesn't sound a right thing to do. What would you recommend me then? I'm on Arch Linux and have 2 rubies installed: $ chruby * ruby-2.2.4 ruby-2.3.1 Maybe I should upgrade it to a slitely newer version? Note that I don't want to break other dependencies in the project. |
Fetching Recent mail by IMAP in rails Posted: 26 Aug 2016 05:29 AM PDT I am trying to fetch new incoming mail through IMAP protocol ..my sample code is bellow-- task :receive_mail_new => :environment do #require 'rubygems' require 'net/imap' imap = Net::IMAP.new('imap.gmail.com', 993, true,nil, false) #imap.authenticate('LOGIN','debasish.industrify2016@gmail.com','****') imap.login('test@example.com', '********') imap.examine('INBOX') imap.search(["RECENT"]).each do |id| envelope = imap.fetch(id, "ENVELOPE")[0].attr["ENVELOPE"] puts "#{envelope.from[0].name}: \t#{envelope.subject}" end imap.logout() imap.disconnect() end when i run this code there is no response when i add this line imap = Net::IMAP.new('imap.gmail.com', 993, true,nil, false) instate of imap.authenticate('LOGIN','test@example.com','****') the error its shows Net::IMAP::NoResponseError: Unsupported AUTHENTICATE mechanism. 15mb877209661ieh can any one help me? |
Keystroke dynamics authentication for Ruby on Rails Posted: 26 Aug 2016 04:10 AM PDT |
ActiveRecord vs SQL raw queries? [on hold] Posted: 26 Aug 2016 06:19 AM PDT What is the difference between ActiveRecord and writing raw queries.?? In which situation one should adopt writing raw queries in rails app . |
Tinymce Rails Paperclip Image upload error Posted: 26 Aug 2016 04:00 AM PDT I am using Tinymce with Paperclip Image Upload feature in my rails application. Tinymce uploads images in my local machine but its not working in production in server. I am getting the following error.. Paperclip::Errors::NotIdentifiedByImageMagickError (Paperclip::Errors::NotIdentifiedByImageMagickError): app/controllers/tinymce_assets_controller.rb:5:in `create' I am using Ubuntu Server and Image uploads works on file upload of form for but its failing in Tinymce. TinyMce Assets Controller class TinymceAssetsController < ApplicationController respond_to :json def create geometry = Paperclip::Geometry.from_file params[:file] image = Image.create params.permit(:file, :alt, :hint) render json: { image: { url: image.file.url, height: geometry.height.to_i, width: geometry.width.to_i } }, layout: false, content_type: "text/html" end end Please help me to find the solution. |
devise redirect after sign up not working Posted: 26 Aug 2016 04:15 AM PDT have gone through some of the answers on stack and also read the devise documentation to implement this. i wanted to Redirect to a specific page on successful sign up (registration). on the devise documentation have added the def after_sign_up_path_for(resource) '/account/new' # Or :prefix_to_your_route end in the application controller and also in the registration contoller but still its not working. what have i done wrong? am using rails 5 with devise master branch |
Unable to log out of clearance gem Posted: 26 Aug 2016 03:42 AM PDT I have recently move my project away from the somewhat bloat devise to clearance, though I am experiencing troubles when attempting to log out I am currently get the error of the route not existing No route matches [GET] "/sign_out" routes resources :passwords, controller: "clearance/passwords", only: [:create, :new] resource :session, controller: "clearance/sessions", only: [:create] resources :users, controller: "clearance/users", only: [:create] do resource :password, controller: "clearance/passwords", only: [:create, :edit, :update] end get "/sign_in" => "clearance/sessions#new", as: "sign_in" delete "/sign_out" => "clearance/sessions#destroy", as: "sign_out" get "/sign_up" => "clearance/users#new", as: "sign_up" constraints Clearance::Constraints::SignedIn.new do root :to => 'shopping/merchants#index', as: :signed_in_root end constraints Clearance::Constraints::SignedOut.new do root to: 'clearance/sessions#new' end view = link_to sign_out_path, method: :delete, class: 'mdl-navigation__link' do i.material-icons> exit_to_app = t('.log_out') |
got 'cannot load such file' when using delayed_job with rubypython Posted: 26 Aug 2016 04:02 AM PDT when I trying to use delayed_jobs to do something with gem 'rubypython ', I got this error: cannot load such file --rubypython. rubypython works well if I didn't use delayed_job I am using: Ruby 2.1.2 Rails 4.1.4 Python 2.6.6 |
Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job.
ReplyDeletefake id usa
Ruby on rails development USA
ReplyDeleteSofhub– We provide our custom software development and designing services in USA & UAE. We are specializing in web designing, mobile app development. Contact us.
Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next..
ReplyDeleteinstagram panel
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
ReplyDeletedoors next
If you are looking for a heating and air conditioning company in the Tulsa County area, Our professional technicians can help you select, install, and maintain equipment to assure efficiency, reliability, and comfort over the lifetime of your products
ReplyDeletetaxi dispatch software
Love what you're doing here guys, keep it up!..
ReplyDeletesaas development company
Thank you very much for keep this information.
ReplyDeletebuild taxi app
For a long time me & my friend were searching for informative blogs, but now I am on the right place guys, you have made a room in my heart! Newcastle air conditioning
ReplyDelete