Rails: Update users via link Posted: 25 Dec 2016 07:43 AM PST I am trying to update a devise record via a link in my view. This is what I've got: = link_to "Update", user_registration_path(current_user, user: {abc: true}), method: :put, remote: true I get the following issue: private method `to_param' called for # How am I able to update this record remotely? |
undefined method `url' for "#<ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":String Posted: 25 Dec 2016 05:34 AM PST I am using Carrierwave to upload picture, after uploaded, I got the error when go to show page: undefined method `url' for "#ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":String <%= image_tag @product.picture.url if @product.picture? %> Here is my code: _form.html.erb <div class="picture"> <%= f.file_field :picture %> </div> product.rb class Product < ApplicationRecord has_many :reviews, dependent: :destroy mount_uploader :picture, PictureUploader end show.html.erb <p id="notice"><%= notice %></p> <p> <strong>Name:</strong> <%= @product.name %> </p> <strong>Picture:</strong> <%= image_tag @product.picture.url if @product.picture? %> </p> <%= link_to 'Edit', edit_product_path(@product) %> | <%= link_to 'Back', products_path %> Anyone know how to solve the problem? Update: picture_uploader.rb # encoding: utf-8 class PictureUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: # version :thumb do # process :resize_to_fit => [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: # def extension_white_list # %w(jpg jpeg gif png) # end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end Here is the version in Gemfile: gem 'carrierwave', '0.11.2' gem 'mini_magick', '4.5.1' gem 'fog', '1.38.0' |
Where can I store classified helpers? Posted: 25 Dec 2016 04:51 AM PST I felt really uncomfortable seeing my helpers grow, so I decided to refactor my helpers and move them into separate classes/modules. To get a better understanding how to refactor this kind of stuff I read a lot about presenters, decorators and so on. Although this helped me a little bit - I am still wondering where to put helper methods that are neither model specific nor controller specific. So for example I have a new class that renders html title tags (across the application) from a yaml file. And it contains some new link helper methods, that are not controller specific. Reading about decorators and presenters it is always assumed I want to present some active record model.. But in this case these are some "application wide" helper methods. So - where can I put these classes and how should I name them ?? |
Devise doesn't destroy users Posted: 25 Dec 2016 06:29 AM PST Trying to install devise for Rails 5 I've encountered an interesting problem. I've installed devise for users (all by instructions). Everything is working properly except one thing. When I'm trying to delete a user, the controller shows a NameError in Users::RegistrationsController#destroy about uninitialized constant User::Application , mentioning the @user.destroy line. It seemed strange so I checked if it's my Rails setup problems or something like that. So I installed an example app from github (sachin's Skeleton) which contained just the same code as mine. It worked perfectly - no errors, users were deleting from db. Some code: # views/users/registrations/edit.html.erb <p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p> # config/routes.rb Rails.application.routes.draw do root 'home#index' devise_for :users end In RegistrationsController I use destroy method from a super class. If you need any other code - just write in comments! Thanks in advance! UPDATE Started DELETE "/users" for 127.0.0.1 at 2016-12-25 13:18:45 +0300 Processing by Users::RegistrationsController#destroy as HTML Parameters: {"authenticity_token"=>"9/qsZDLoIIVCwckYnbk2418bupp0+v/1cnbERbgfBmRwmf/CHIas47WX9au+zXfyTWMcUF/dXpDf52rKBC0eZw=="} User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 8], ["LIMIT", 1]] (0.1ms) BEGIN (0.1ms) ROLLBACK Completed 500 Internal Server Error in 67ms (ActiveRecord: 0.3ms) NameError (uninitialized constant User::Application): app/controllers/users/registrations_controller.rb:30:in `destroy' Rendering /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout Rendering /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb Rendered /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (7.1ms) Rendering /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb Rendered /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.3ms) Rendering /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb Rendered /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.7ms) Rendered /var/lib/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (45.7ms) Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:19:55 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:03 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:03 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:09 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:09 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:46 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:48 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:53 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:20:53 +0300 8 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:21:07 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:21:10 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:21:50 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:21:57 +0300 #<User:0x000000059ccb38> Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:22:08 +0300 Started PUT "/__web_console/repl_sessions/d6f9eddc77dfe831182fe552ca93e79f" for 127.0.0.1 at 2016-12-25 13:22:09 +0300 Started DELETE "/users" for 127.0.0.1 at 2016-12-25 13:22:53 +0300 Processing by Users::RegistrationsController#destroy as HTML Parameters: {"authenticity_token"=>"9/qsZDLoIIVCwckYnbk2418bupp0+v/1cnbERbgfBmRwmf/CHIas47WX9au+zXfyTWMcUF/dXpDf52rKBC0eZw=="} User Load (4.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 8], ["LIMIT", 1]] In RegistrationsController it's just: def destroy super end |
Can I move this code from erb to the model? Posted: 25 Dec 2016 02:45 AM PST I have 2 models Auteur and Biblio that both have_and_belongs_to_many of each other. In the template displaying the Authors (auteur) and its books (biblio), I have this code : <% @auteurs.each do |e| %> <p><%= e.nom_complet %>, <i> <%= e.biblios.map{|l| l.titre }.join(', ') %></i>, <%= e.biblios.map { |l| l.lieu }.join(', ') %>, <%= e.biblios.map { |l| l.annee }.join(', ') %> </p> <% end %> As each biblio has 8 fields and can belong to different types according to its form of publication and type of content, this would lead to doing a lot of map and if statements in erb. Although this works fine, there must be a better way of doing this. Thanks |
Rails database migration error Posted: 25 Dec 2016 07:01 AM PST I wanna get started with ror but this problem seems unsolvable. I know there are many threads about it this database error but none of the solutions appear to work out. I now searched through the forums all afternoon, with no success. I basically just perform the first tasks from the textbook, which are as follows: I create a new RoR project (Windows 10, SQLite3) with rails new depot Then I create a scaffold in this project with the following code: rails generate scaffold Product title:string description:text image_url:string price:decimal And as i test the application I get the db:migrate error. I tried rake db:migrate , db:rollback , db:drop and then db:create , I checked the migration file for mistakes, but nothing appears to work. I assume the solution should be quite simple, since the application should be as uncomplex as it gets at this state, but I just cannot get behind the secret it appears. Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=test from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:586:in `load_schema_if_pending!' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:592:in `block in maintain_test_schema!' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:823:in `suppress_messages' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:597:in `method_missing' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:592:in `maintain_test_schema!' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_help.rb:15:in `<top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `block in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `require' from C:/Users/Flori/Desktop/bsp/test/test_helper.rb:3:in `<top (required)>' from C:/Users/Flori/Desktop/bsp/test/controllers/products_controller_test.rb:1:in `require' from C:/Users/Flori/Desktop/bsp/test/controllers/products_controller_test.rb:1:in `<top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:11:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:11:in `block in require_files' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:10:in `each' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:10:in `require_files' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/minitest_plugin.rb:86:in `plugin_rails_init' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/minitest-5.10.1/lib/minitest.rb:80:in `block in init_plugins' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/minitest-5.10.1/lib/minitest.rb:78:in `each' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/minitest-5.10.1/lib/minitest.rb:78:in `init_plugins' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/minitest-5.10.1/lib/minitest.rb:129:in `run' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/test_unit/minitest_plugin.rb:73:in `run' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/minitest-5.10.1/lib/minitest.rb:62:in `block in autorun' |
onclick change parent url ruby on rails 4 Posted: 25 Dec 2016 02:03 AM PST Goal: on click open new tab and change url of parent page. <%= search_form_for @q, url: pages_auto_path do |f| %> <%= f.search_field(:name) %> <%= f.button :submit, :id => "changeit", :formtarget => "_blank" do %> Search <% end %> <% end %> application.js file $("#changeit").on("click", function(){ window.location.replace("http://www.google.com"); }); after clicking search button , new tab open but parent page stay same. i need parent page to redirect other url. Any idea, what is wrong here ? |
Sidekiq on Mac not working Posted: 25 Dec 2016 03:55 AM PST I'm using Sidekiq for background job with Rails 5 and trying to run on MacOS. Currently I meet problem that my sidekiq worker not work. First situation: I don't start sidekiq service. So after I run a sidekiq worker, I go to sidekiq panel (/sidekiq ) I see one enqueued job. Each time I repeat this task, one enqueued job is added. Second situation: I start to run sidekiq from command line using command: bundle exec sidekiq -C ./config/sidekiq.yml Here is my sidekiq.yml file: --- :logfile: ./log/sidekiq.log :queues: - default At this time, I go to sidekiq panel, I see no enqueued job nor processed job. This looks strange to me. It looks like sidekiq doesn't do anything. Please help me explain why. @Edit: I have tested, the problem because I use ActiveRecord for querying. I don't know why it is fail. |
Look for the top ten best selling products Posted: 24 Dec 2016 11:57 PM PST I need to search the top 10 items sold, I have been investigating and I found a method called top that can make this possible, I try to apply it but I get this error: SyntaxError (/home/luis/sites/AdvanceControld/app/models/detalleve.rb:38: syntax error, unexpected '(', expecting keyword_end query = select top 10('detallevet.Articulo') What would be the best way to do this search? def self.best_seller(params) query = select top 10('detallevet.Article') .joins('left outer join venta ON venta.Documento=detallevet.Docto and venta.RutaId=detallevet.RutaId') .where("(venta.RutaId = :rutaId or :rutaId = '') AND (venta.IdEmpresa = :idempresa)",{rutaId: params[:search], idempresa: params[:search0]}) query = query.where('venta.Fecha >= ? AND venta.Fecha <= ?', (params[:search1].to_date).strftime('%Y-%m-%d'), (params[:search2].to_date).strftime('%Y-%m-%d')) if params[:search1].present? and params[:search2].present? query end |
How to run warbler (jruby on rails) on different port rather than 8080 Posted: 25 Dec 2016 04:26 AM PST I created a war file named my_sample.war and run java -jar my_sample.war . It runs at port 8080 as default value. What do I do to change it to port 3000 . Thanks! |
Update checkbox options using ajax in Rails 5 Posted: 25 Dec 2016 03:39 AM PST A little explanation of the app. It's a tour registration system for a multi-campus organization. Someone should be able to come in and select a campus from a select box and have the "options" checkboxes and "tour dates" radio buttons update to be campus specific. I've got the script triggering when someone changes the select box but it keeps returning a 404 when I go to the path and the url looks really wonky. Also I know I'm going to run into trouble when I try to .html replace the section with new options. Ok without further ado, here's the code. Any guidance would be appreciated! _form.html.erb ... <div class="field"> <%= label_tag 'Campus' %> <%= select_tag 'campuses', options_from_collection_for_select(@churches, 'id', 'name', selected: (@registration.event.church.id unless @registration.event.nil?) )%> </div> <div class="field"> <%= label_tag 'Areas of Interest' %> <div id="options_container"> <%= f.collection_check_boxes :option_ids, @options, :id, :ministry_area do |b| %> <div class="collection-check-box"> <%= b.check_box %> <%= b.label %> </div> <% end %> </div> </div> <div class="field"> <%= label_tag 'Tour Dates' %> <div id="events_container"> <%= f.collection_radio_buttons(:event_id, @events, :id, :event_datetime) do |b| %> <div class="radio"> <%= b.radio_button + " " + b.label %> </div> <% end %> </div> </div> <div class="actions"> <%= f.submit params[:action] == 'edit' ? "Update Registration" : "Register", class: 'button' %> </div> <% end %> <script> $(document).ready(function () { $('#campuses').change(function () { $.ajax({ url: "<%= update_campus_options_and_events_path %>", data: { campus_id: $('#campuses').val() }, dataType: "script" }); }); }); </script> routes.rb Rails.application.routes.draw do resources :registrations root 'registrations#index' get 'update_campus_options_and_events', to: 'registrations#update_campus_options_and_events' end registrations_controller.rb ... def update_campus_options_and_events @events = Event.find(params[:campus_id]) @options = Option.find(params[:campus_id]) respond_to do |format| format.html format.js {} end end ... update_campus_options_and_dates.js.erb console.log('Options changed via ajax'); $('#options_container').html("<%= escape_javascript(<%= f.collection_check_boxes :option_ids, @options, :id, :ministry_area do |b| %>) %>"); $('#events_container').html("<%= escape_javascript(<%= f.collection_radio_buttons(:event_id, @events, :id, :event_datetime) do |b| %>) %>"); |
Limiting the number of characters per line in css Posted: 24 Dec 2016 11:57 PM PST How can I make sure that 50 characters are shown in block (width:100px; ) with CSS if User posts 50 characters on one line. Now, my view is below. <div class='example-wrapper'> <%= simple_format(@user.content , class:'example') %> </div> If User posts 50 characters on one line(without making a line break) in @user.content, it is sticking out from browser.I don't mean that I use overflow:hidden; . Although I use white-space:normal; , nothing changes. The error is shown the following picture. I want to show all characters. Please tell me how to do it. Now, scss is below. .example-wrapper{ background-color:red; max-width:100px; } .example{ max-width:100px; white-space:normal; } |
How to marge this two def index Posted: 24 Dec 2016 08:22 PM PST I've 2 different index actions, can anyone help me to merge this? First def index (for tags): def index if params[:tag] @posts = Post.tagged_with(params[:tag]) else @posts = Post.all end end Second def index (for categories): def index if params[:category].blank? @posts = Post.all else @category_id = Category.find_by(name: params[:category]).id @posts = Post.where(category_id: @category_id) end end |
Rails cache ActiveRecord result Posted: 25 Dec 2016 02:09 AM PST My current homepage displays all available categories and all of the number of posts each category has. This of course is having a performance hit on the website and i was just wondering if this could be cached at all? I don't mind if the cache is a little out of date and if the number of posts isn't 100% accurate at every refresh, but i would like it to only make the query every 30 minutes or so. |
Rails: rake error "/gems/faker.." Posted: 24 Dec 2016 04:29 PM PST With any "rake something" command I get this error /app/vendor/bundle/ruby/2.2.0/gems/faker-1.7.0/bin/rake:17:in `<top (required)>' /app/vendor/bundle/ruby/2.2.0/gems/faker-1.7.0/bin/rake:17:in `load' This error repeat multiple time. Notes: |
Ruby on Rails post path turns into get path Posted: 24 Dec 2016 05:19 PM PST I am using Ruby on Rails 5 for a personal project and I can't seem to get my link routes to the correct controller action and client action. <div class="admin-users index"> <h2>Admin Users</h2> <%= image_tag('plus_sign.png', :size => '11x11', :alt => '+') %> <%= link_to("Add New Admin User", new_admin_user_path, :class => 'action new') %> <table class="listing" summary="Admin user list"> <tr class="header"> <th>Username</th> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> <% @admin_users.each do |admin_user| %> <tr> <td><%= admin_user.username %></td> <td><%= admin_user.name %></td> <td><%= mail_to(admin_user.email) %></td> <td class="actions"> <%= link_to("Edit", edit_admin_user_path(admin_user), :class => 'action edit') %> <%= link_to("Delete", delete_admin_user_path(admin_user), :class => 'action delete') %> <%= link_to("Follow User", followings_path(:followed_id => admin_user), :method => :post)%> </td> </tr> <% end %> </table> </div> I have a link action to make post requests to create a binding between two users. Rails.application.routes.draw do resources :followings, :except => [:show, :update, :delete, :new] do end I used resources routing to make things simpler for me, unfortunately when I click on Follow User, my post request turns into a get request and I can't add any user to my following list. http://localhost:3000/followings?followed_id=5 When I click to the Follow User button, it leads me to the url above, which is fine, but then after looking at the console I see it's a GET request. Started GET "/followings?followed_id=5" for ::1 at 2016-12-24 18:16:26 -0400 ActiveRecord::SchemaMigration Load (1.0ms) SELECT `schema_migrations`.* FROM `schema_migrations` Processing by FollowingsController#index as HTML Parameters: {"followed_id"=>"5"} AdminUser Load (0.0ms) SELECT `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 1 LIMIT 1 Rendering followings/index.html.erb within layouts/admin Following Load (0.0ms) SELECT `followings`.* FROM `followings` WHERE `followings`.`admin_user_id` = 1 AdminUser Load (1.0ms) SELECT `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 3 LIMIT 1 Rendered followings/index.html.erb within layouts/admin (64.0ms) Completed 200 OK in 542ms (Views: 448.4ms | ActiveRecord: 10.0ms) Here's the following controller: class FollowingsController < ApplicationController layout 'admin' def index admin_user = AdminUser.find(session[:user_id]) @user = admin_user end def create current_user = AdminUser.find(session[:user_id]) @following = current_user.following.build(:followed_id => params[:followed_id]) if @following.save flash[:notice] = "Added user." redirect_to root_url else flash[:notice] = "Cannot add user." redirect_to(admin_users_path) end end def destroy current_user = AdminUser.find(session[:user_id]) @following = current_user.followings.find(params[:id]) @following.destroy flash[:notice] = "Removed user." redirect_to root_url end end Can't figure why it's doing this. |
Calculate and order the number of referrals for each referrer Posted: 24 Dec 2016 05:45 PM PST I'll preface this by saying I'm new to rails and development. Overview I have a simple referral system, and I want to calculate the number of times each subscriber has referred someone else, then put all subscribers in descending order based on the number of referrals. Details Here's my Subscribers table: | id | email | referred_by | referred_by contains the subscriber_id of the referring subscriber. What I want is a method / query that loops through every subscriber in the table and: - Counts the number of times their id appears in the
referred_by columns. - Orders subscribers by the total number of referrals they have.
I was thinking along the lines of the below, but part of my problem is that I don't know where and how I can test methods and queries outside of the codebase, so I don't how to test this. I assume in the console, but I don't understand how to do multi-part methods or queries there. Subscriber.all.each do |referrer| Subscriber.all.each do |subscriber| if referrer.id == subscriber.referred_by referrals += 1 else next end end end # Then order descending |
MySQL, Highcharts: “operand should contain 1 column(s):” error (follow up) Posted: 24 Dec 2016 02:44 PM PST I am trying to render data on to a spline chart by collecting an array of id's: Controller def student_feedback difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty) @homeworks = HomeworkStudent.where("homework_id = (?)", difficulty_ids).first end The table I am targeting is called homework_students: create_table "homework_students", force: :cascade do |t| t.integer "school_user_id", limit: 4, null: false t.integer "homework_id", limit: 4, null: false t.datetime "completed_on" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "completed", limit: 1 t.integer "difficulty", limit: 4 t.integer "interest", limit: 4 end Each student has many different homeworks and they can assign a difficulty value in the difficulty column for each. I am looking to graph this data for each student. So in the above controller action I am plucking difficulty figures (1 - 5) for each piece of homework the current user is associated with in an array. In my chart: ... } }, series: [{ name: 'Difficulty', data: [<%= @homeworks.to_json %>] }] }); I tried changing action to this: def student_feedback difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty) @homeworks = HomeworkStudent.where(["homework_id = ?", difficulty_ids]).first end I keep getting this error: Mysql2::Error: Operand should contain 1 column(s): SELECT `homework_students`.* FROM `homework_students` WHERE (homework_id = (4,2,1,2,3)) ORDER BY `homework_students`.`id` ASC LIMIT 1 The data being collected is correct. Though it says "homework_id = 4,2.." (this is not correct, those are the difficulty values). I suspect this is just a syntax error. I have toyed around a little bit. Can provide more code if needed. I understand the problem but it's just the syntax... Much appreciate any help. Thanks |
Limiting the number of characters per line Posted: 24 Dec 2016 03:53 PM PST How can I make sure that 50 characters are shown in block (width:100px;) with CSS if User posts 50 characters on one line. Now, my view is below. <div class='example-wrapper'> <%= simple_format(@user.content , class:'example') %> </div> If User posts 50 characters on one line(without making a line break) in @user.content, it is sticking out from browser.I don't mean that I use overflow:hidden;.Although I use white-space:normal; , nothing changes. Please tell me how to do it. Now, scss is below. .example-wrapper{ background-color:red; max-width:100px; } .example{ max-width:100px; white-space:normal; } |
Bi-Directional has_and_belongs_to_many on a Single Model in Rails Posted: 24 Dec 2016 06:22 PM PST I have User model and I want to create friendship between users. I've achieved this using has_and_belongs_to_many has_and_belongs_to_many :friends, class_name: 'User', foreign_key: :friend_id And I have table for this association: create_table :users_users do |t| t.uuid :user_id, null: false t.uuid :friend_id, null: false t.timestamps end When I get friends via user.friends I need to have association where current user is in user_id column or friend_id. My current solution returns me only records where user is in friend_id table. I have two solution for this: - Duplicate records [{user_id: 1, friend_id: 2}, {user_id: 2, friend_id: 1}]
- Override user.friends method and return my custom query
Both solution are not elegant and optimal. I've read article about it, but the solution from this article is very complicated. Is there any other solutions for this problem? I'm using rails 5. |
Customizing routes for nested resources Posted: 24 Dec 2016 03:01 PM PST I currently have the following resources: routes.rb Rails.application.routes.draw do resources :store do resources :candy end end As you know, this generates routes for 6 HTTP Actions, including the nested store/store_id/candy/... routes. This is fine with me, however I want only use GET and POST instead of PATH/PUT and DELETE POST store/destroy/:id and POST store/update/:id would be the ideal behavior for me. First of all, is this breaking convention and if not, is there an easy way to generate such routes? |
MySQL, Highcharts: "operand should contain 1 column(s):" error Posted: 24 Dec 2016 01:16 PM PST I am trying to render data on to a spline chart by collecting an array of id's: Controller def student_feedback difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty) @homeworks = HomeworkStudent.where("homework_id = (?)", difficulty_ids).first end In my chart: ... } }, series: [{ name: 'Difficulty', data: [<%= @homeworks.to_json %>] }] }); But I keep getting this error: Mysql2::Error: Operand should contain 1 column(s): SELECT `homework_students`.* FROM `homework_students` WHERE (homework_id = (4,2,1,2,3)) ORDER BY `homework_students`.`id` ASC LIMIT 1 The data being collected is correct. Is this just a syntax error? I have toyed around a little bit. Removing the brackets from "homework_id = ?" gives same result...can provide more code if needed. Thanks Thanks @the12 Tried this def student_feedback difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty) @homeworks = HomeworkStudent.where(["homework_id = ?", difficulty_ids]).first end But this returns error ` Mysql2::Error: Operand should contain 1 column(s): SELECT `homework_students`.* FROM `homework_students` WHERE (homework_id = 4,2,1,2,3) ORDER BY `homework_students`.`id` ASC LIMIT 1` Where it says homework_id = 4,2,1... these numbers are actually from a column called "difficulty" - maybe something is off in the statement above in the controller? |
Clearance gem not displaying flash messages (Ruby on Rails 5.0.1) Posted: 24 Dec 2016 12:24 PM PST How do I display flash messages when using the clearance gem for user authentication? I have this code set in my view/layouts/application.html.erb inside the body tags: <% flash.each do |key, value| %> <div class="alert alert-<%= key %>"><%= value %></div> <% end %> I have checked the docs and wiki but couldn't find anything. When I create a user or login/logout there is no flash message displayed. |
Ruby / Rails (5.0.0.1) - Material Design Lite - Text Field Error Messages Posted: 24 Dec 2016 12:23 PM PST Ruby / Rails (5.0.0.1) - Material Design Lite - Text Field Error Messages I am constructing a signup form. I have errors displaying. I would like to stlye these errors using material design specifications. I would like the text field line to transform red (or accent color) and display the span "mdl-textfield__error" message. Any additional resources would be appreciated. SIGNUP FORM <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <%= f.email_field :email, class:'mdl-textfield__input', type:'text', id:'email' %> <label class="mdl-textfield__label" for="email">EMAIL</label> <span class="mdl-textfield__error">INVALID EMAIL</span> </div> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <%= f.password_field :password, class:'mdl-textfield__input', type:'password', id: 'password' %> <label class="mdl-textfield__label" for="password">PASSWORD</label> <span class="mdl-textfield__error">INVALID PASSWORD</span> </div> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <%= f.password_field :password_confirmation, class:'mdl-textfield__input', type:'password', id: 'password' %> <label class="mdl-textfield__label" for="password">PASSWORD (CONFIRMATION)</label> <span class="mdl-textfield__error">INVALID CONFIRMATION</span> </div> CURRENT ERROR MESSAGE DISPLAY TARGET ERROR MESSAGE DISPLAY |
How to build AJAX data from url params? Posted: 25 Dec 2016 05:08 AM PST Goal: if no param present, do query (this is working), but if param is present do a different query. It seemed pretty straight forward: pass the param (or not), in the controller check if the param existed, if so do new query, if not, do old query. Pass the data onto AJAX and coffeescript. By looking at my log it appears that rails uses the controller twice - once on initial page load and a second time when it has the AJAX data. Since it's doing this twice, I seem to be loosing my param value when it goes through a second time. Any suggestions for how to fix this? relevant part of my controller @pId = params[:id] puts params.inspect if @pId.present? puts "-- Id present --" @points = Point .select('points.genus, points.species, points.cultivar, points.common_name, types.type_name') .where(id: @pId) .eager_load(:type) else puts "** Id not present **" @points = Point .select('points.genus, points.species, points.cultivar, points.common_name, types.type_name') .where("types.type_name like 'Tree-%' or types.type_name like 'Shrub-%' or types.type_name like 'Perennial' or types.type_name like 'Fern' or types.type_name like 'Vine-%'") .order(:id) .eager_load(:type) end feature_collection = Point.to_feature_collection @points @geojson = RGeo::GeoJSON.encode(feature_collection) respond_to do |format| format.json { render json: @geojson } format.html end relevant part of my coffeescript $.ajax dataType: 'text' url: 'map.json' send: () -> $('#loading').show() complete: () -> $('#loading').hide() success: (data) -> L.geoJSON(JSON.parse(data), pointToLayer: plantToMarker) Update Now that I'm not cold medication and my head is no longer fuzzy, I'm going to try again. I suspect I'm either missing something conceptually is the page load cycle, or I don't understand how AJAX works (also likely, because this is my first time working with it). If I use the url localhost:3000/map my page displays, loads a JS library for mapping, and plants_controller.rb does a query with results in a couple hundred plant points getting drawn on the map using my coffeescript. That's working just fine. I want everything to remain the same when I use the url localhost:3000/map?id=3 except rather than the query returning many points it should only return #3. I always thought this would be a linear process that fired once - sort of like page loads, controller is processed and data generated, js library loaded, ajax sent, js finished drawing the map. If I understand what I see in my logs, we seem to be going through the controller twice - the first time, if the id param is present, it processed the code. However, on the second pass through it doesn't find the id, and ends up loading all the plant points. I can't for the life of me understand why the controller is getting access twice, and why the second time it is failing to recognize the id. @joel I tried to implement your suggestion and I'm either not doing it correctly, or it isn't helping respond_to do |format| if @pId.present? format.json { render json: @geojson, data: @pId} else format.json { render json: @geojson } end format.html end |
Ruby/GEM install Middleman error: The 'fast_blank' native gem requires installed build tools Posted: 24 Dec 2016 11:49 AM PST I'm trying to install https://middlemanapp.com/ using "gem", but getting the following error. I read the link in the error message, but I can't find any solution. C:\Users\user1>ruby -v ruby 2.3.3p222 (2016-11-21 revision 56859) [x64-mingw32] C:\Users\user1>gem -v 2.5.2 C:\Users\user1>gem install middleman Fetching: bundler-1.13.6.gem (100%) Successfully installed bundler-1.13.6 Fetching: rack-2.0.1.gem (100%) Successfully installed rack-2.0.1 Fetching: tilt-2.0.5.gem (100%) Successfully installed tilt-2.0.5 Fetching: erubis-2.7.0.gem (100%) Successfully installed erubis-2.7.0 Fetching: fast_blank-1.0.0.gem (100%) ERROR: Error installing middleman: The 'fast_blank' native gem requires installed build tools. Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit' |
Storing Google Maps geo data with Rails / PostGIS / RGeo Posted: 24 Dec 2016 11:06 AM PST Having trouble implementing Daniel Azuma's solution for handling Google Maps geo data with RGeo / Rails. SETUP locations table: create_table "locations", force: :cascade do |t| t.string "name", t.geometry "polygon", limit: {:srid=>3857, :type=>"polygon"} end Location class: class Location < ActiveRecord::Base # Create a simple mercator factory. This factory itself is # geographic (latitude-longitude) but it also contains a # companion projection factory that uses EPSG 3857. FACTORY = RGeo::Geographic.simple_mercator_factory # To interact in projected coordinates, # just use the "polygon" attributes directly. def polygon_projected self.polygon end def polygon_projected=(value) self.polygon = value end # To use geographic (lat/lon) coordinates, # convert them using the wrapper factory. def polygon_geographic FACTORY.unproject(self.polygon) end def polygon_geographic=(value) self.polygon = FACTORY.project(value) end def self.from_geojson(geojson) location = Location.new decoded_polygon = RGeo::GeoJSON.decode(geojson, json_parser: :json, geo_factory: RGeo::Geographic.simple_mercator_factory) location.polygon_geographic = decoded_polygon return location end end initializers/rgeo.rb: RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config| # By default, use the GEOS implementation for spatial columns. config.default = RGeo::Geos.factory_generator end (Solution derived from here and here) ISSUE So here we go- I create a new Location object from a geojson shape containing coordinates from a Google Map: manhattan_polygon_data = '{"type":"Polygon","coordinates":[[[-73.9784998975546,40.7367992185915],[-73.9808911983494,40.7334453322506],[-73.9899687850649,40.7350399153528],[-73.9894998975546,40.7395992185915]]]}' location = Location.from_geojson(manhattan_polygon_data) At this point, all our geo properties are working properly: # Test geo properties: location.polygon_projected => #<RGeo::Geos::CAPIPolygonImpl:0x3fc428c0c7dc "POLYGON ((-8235248.938246019 4973596.780357394, -8235515.136632829 4973104.057720993, -8236525.648963631 4973338.316345756, -8236473.452644745 4974008.150049943, -8235248.938246019 4973596.780357394))"> location.polygon_geographic => #<RGeo::Geographic::ProjectedPolygonImpl:0x3fc425d137a0 "POLYGON ((-73.9784998975546 40.73679921859151, -73.9808911983494 40.73344533225058, -73.9899687850649 40.73503991535281, -73.9894998975546 40.73959921859151, -73.9784998975546 40.73679921859151))"> But when we save and re-read from the database, something goes wrong: # Save and retrieve from DB: location.save! location_from_db = Location.find(location.id) # Test geo properties again: location_from_db.polygon_projected => #<RGeo::Geos::CAPIPolygonImpl:0x3fc425cfb664 "POLYGON ((-8235248.938246019 4973596.780357394, -8235515.136632829 4973104.057720993, -8236525.648963631 4973338.316345756, -8236473.452644745 4974008.150049943, -8235248.938246019 4973596.780357394))"> location_from_db.polygon_geographic RGeo::Error::InvalidGeometry: You can unproject only features that are in the projected coordinate space. from /usr/local/lib/ruby/gems/2.3.0/gems/rgeo-0.5.3/lib/rgeo/geographic/factory.rb:270:in `unproject' Given that the projected geometries of both objects are equivalent, I'm not sure why the latter unproject operation is failing. |
Rails server not running Unable to load thrift_native extension Posted: 24 Dec 2016 11:31 AM PST I have a rail project which runs on ruby but when i try to run it it says Unable to load thrift_native extension. Defaulting to pure Ruby libraries. Exiting /usr/lib/ruby/vendor_ruby/rack/handler.rb:54:in `default': uninitialized constant Rack::Handler::REQUEST_METHOD (NameError) from /var/lib/gems/2.3.0/gems/rack-1.4.6/lib/rack/server.rb:272:in `server' from /var/lib/gems/2.3.0/gems/railties-3.2.22.3/lib/rails/commands/server.rb:59:in `start' from /var/lib/gems/2.3.0/gems/railties-3.2.22.3/lib/rails/commands.rb:55:in `block in <top (required)>' from /var/lib/gems/2.3.0/gems/railties-3.2.22.3/lib/rails/commands.rb:50:in `tap' from /var/lib/gems/2.3.0/gems/railties-3.2.22.3/lib/rails/commands.rb:50:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' I dont know how to solve this problem and where the problem occurs? My ruby version is : ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu] My rails version is : Rails 5.0.1 All gems list are in this: link |
CakePHP DebugKit equivalent on Rails? Posted: 24 Dec 2016 09:42 AM PST If there any gem that offer a "debug" toolbar on browser, not to pause execution, just to have an overview of what happen on the request, CakePHP have a really nice plugin called DebugKit for this, it displays something like: You can see variables that are scoped to the view, the time that it took to process each part of the applicatoin, a sql log, information about the session and the requests. Sometimes something like that would be very useful, but I'm not able to find something like that for rails, any gem you are aware of? |
Rails pattern for destroying relationship between two ActiveRecord objects Posted: 24 Dec 2016 11:18 AM PST Say I have two models, A and B, where each has a has_and_belongs_to_many relationship with the other. That is, some A objects and B objects are "connected". What would be the proper way to offer a route to destroy this relationship? It doesn't really make sense to be a destroy action on A or B's controller since we aren't destroying A or B. Is there some sort of standard way to do this? |
No comments:
Post a Comment