undefined local variable or method 'book' Posted: 02 Oct 2016 07:40 AM PDT I am new to rails and trying to create a sample app. I have App/routes.rb Rails.application.routes.draw do resources :books do book.resources :comments, :only => :create #root 'books#index' end end Not sure why I am getting the following error /bookshelf/config/routes.rb:3:in `block (2 levels) in <top (required)>': undefined local variable or method `book' for #<ActionDispatch::Routing::Mapper:0x007fdebb03e728> (NameError) |
Routting error in rails-cpanel Posted: 02 Oct 2016 07:20 AM PDT i deployed rails application in cpanel and run rails project but always server return to me this error 'No route matches "/index.html.var" with {:method=>:get}' http://railsbama.tk/ notice: this project is hello world and has one controller('home') and one action 'index' only return 'hello world' |
Replace rails param value using JavaScript Posted: 02 Oct 2016 07:14 AM PDT I have a search form that I would like to have the "last searched values" pre-pop the fields when the user submits a search (The search form and the results are on the same page). If there is no previous search, the fields have placeholder values. Search Field <%= text_field_tag(:search_zip, nil, placeholder: " Zip Code", class: "common_search_field search_zip", onkeypress: "return isNumber(event);", maxlength: "5", required: true, value: params[:search_zip]) %> Submit Button <%= submit_tag("Search", class: "search_submit_btn", onclick: "prePopSearchForm();") %> JavaScript function prePopSearchForm(){ "<%= params[:search_zip] %>" = $(".search_zip").val(); } The problem is the params[:search_zip] keeps the original params[:search_zip] value in the :search_zip form-field. I would like to take the current value when the submit button is clicked, and assign it as the params[:search_zip] value. I am new to Rails & JavaScript, so if this is not best practice I would appreciate a push in the right direction, thank you. |
Spree 3.1: Adding select tag to shipment form in delivery step Posted: 02 Oct 2016 06:59 AM PDT I am trying to add one more select tag for city in shipment form in checkout delivery. #views/spree/checkout/_delivery.html.erb <%= form.fields_for :shipments do |ship_form| %> <% ship_form.object.shipping_rates.each do |rate| %> <tr class="stock-item"> <td class="shipment-button"><%= ship_form.radio_button :selected_shipping_rate_id, rate.id %></td> <td class="rate-name"><%= rate.name %></td> <td class="item-qty"></td> <td class="rate-cost"><%= rate.display_cost %></td> </tr> <% if rate.shipping_method_id == 4 %> <tr id="city" style="display: none"> <td></td> <td> <%= ship_form.select :selected_city_id, options_from_collection_for_select(@cities, "id", "name"), { :include_blank => true }, { :class => "select-city" } %> </td> <td></td> <td></td> </tr> <% end %> <% end %> Select box is for choosing city where shipping method is available. I added new column in table spree_shipments and I also added method selected_city_id in models/spree/shippment.rb and permitted new parameters in initializer. But when I try to get @order.shipments.order("created_at").last.selected_city_id I get NoMethodError: undefined method selected_city_id . Prams after submit looks like this: "order"=>{ "shipments_attributes"=>{ "0"=>{"selected_city_id"=>"10", "selected_shipping_rate_id"=>"10", "id"=>"4"} } } I think I'm missing something in here... Please can someone help me, how to save selected_city_id in db? Should it be saved in different table (spree_shipping_rates)? Thanks |
Testing newly injected content with Rspec and Capybara Posted: 02 Oct 2016 07:20 AM PDT We're using react components in our Rails views, one of which when a button is clicked renders another component in its place. Ideally we want to back these up with Rspec feature tests but when the button is clicked and the new component is renders the value of page isn't updated to reflect this. Is there a way with Rspec/Capybara to get the newly injected content after the new react component as rendered? Here's the snippet: scenario 'users should be able to move to step 2', js: true do sign_in_with 'test@test.com', 'testpassword' visit new_path fill_in 'name', with: 'Test' select "Category One", :from => "dropdown" click_button 'Next' expect(page).to have_content('New Content') end |
Rails app tries to GET "/users/logo.png" and shows ActiveRecord::RecordNotFound (Couldn't find User with 'id'=logo) with every submit Posted: 02 Oct 2016 07:12 AM PDT So at every submit request my rails server shows it is trying to get the logo and then shows there is no user with id = logo.png . Can somebody please help me! Detailed error message: Started GET "/users/2" for 127.0.0.1 at 2016-10-02 19:01:18 +0530 Processing by UsersController#show as HTML Parameters: {"id"=>"2"} User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 Rendered users/show.html.erb within layouts/application (1.8ms) Rendered layouts/_header.html.erb (0.0ms) Rendered layouts/_sidebar.html.erb (1.0ms) Completed 200 OK in 130ms (Views: 126.9ms | ActiveRecord: 0.5ms) Started GET "/users/logo.png" for 127.0.0.1 at 2016-10-02 19:01:18 +0530 Processing by UsersController#show as PNG Parameters: {"id"=>"logo"} User Load (1.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 0 LIMIT 1 Completed 404 Not Found in 3ms (ActiveRecord: 1.0ms) ActiveRecord::RecordNotFound (Couldn't find User with 'id'=logo): app/controllers/users_controller.rb:43:in `show' Here is my routes file: Rails.application.routes.draw do root 'dashboard#show' get 'signup' => 'users#new' get 'admins' => 'users#admins_dashboard' delete 'users' => 'users#destroy' get '/users/edit/:id' => 'users#edit' resources :users get 'login' => 'sessions#new' post 'login' => 'sessions#create' delete 'logout' => 'sessions#destroy' end My controller action for users: def show @user = User.find(params[:id]) end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to '/' else redirect_to '/signup' end end the model for users: class User < ActiveRecord::Base has_secure_password def admin? self.role == 'admin' end end |
Mailer Stopped after upgrading to Rails 5 Posted: 02 Oct 2016 06:44 AM PDT I've updated from 4.2.3 to Rails 5 and my mailers stopped working. I'm looking at the logs and can't figure out what's wrong. I've followed the guides: http://guides.rubyonrails.org/action_mailer_basics.html and this article: https://hashrocket.com/blog/posts/how-to-upgrade-to-rails-5 The order mailer is generated when a purchase is created. Changed mailer from Class OrderMailer < ActionMailer::Base to class OrderMailer < ApplicationMailer Added layouts/mailer.html.erb and layouts/mailer.text.erb This is what I'm getting in the logs: [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Performing ActionMailer::DeliveryJob from Async(mailers) with arguments: "OrderMailer", "purchase", "deliver_now", #<GlobalID:0x007fdb4c2072e8 @uri=#<URI::GID gid://myapp/Purchase/27>> Completed 302 Found in 1549ms (ActiveRecord: 34.4ms) [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Order Load (0.2ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT ? [["id", 88], ["LIMIT", 1]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] CACHE (0.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT ? [["id", 88], ["LIMIT", 1]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] OrderStatus Load (0.2ms) SELECT "order_statuses".* FROM "order_statuses" WHERE "order_statuses"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Rendering order_mailer/purchase.html.erb within layouts/mailer [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] OrderItem Load (0.2ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 88]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Product Load (0.2ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT ? [["active", true], ["id", 78], ["LIMIT", 1]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] CACHE (0.0ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 88]] [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] CACHE (0.0ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT ? [["active", true], ["id", 78], ["LIMIT", 1]] Started GET "/purchases/27" for 73.49.113.165 at 2016-10-02 13:04:52 +0000 [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Rendered order_mailer/purchase.html.erb within layouts/mailer (359.5ms) [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] OrderMailer#purchase: processed outbound mail in 383.6ms [ActiveJob] [ActionMailer::DeliveryJob] [7f0cde71-d06c-4bce-be2f-c081e36c0817] Performed ActionMailer::DeliveryJob from Async(mailers) in 384.2ms application_mailer.rb class ApplicationMailer < ActionMailer::Base default from: "info@storeemailhere.com" layout 'mailer' end order_mailer.rb class OrderMailer < ApplicationMailer default from: "Store name" def purchase(purchase) @purchase = purchase @order = @purchase.order @user = @purchase.user @order_items = @order.order_items @order = Order.find(@purchase.order_id) mail( to: purchase.customer_email, bcc: 'myemail@email.com', subject: "Your order# HSN-016-#{@order.id}, Status: #{@order.order_status.name}" ) end end models/purchase.rb class Purchase < ApplicationRecord after_create :purchase_mailer def purchase_mailer OrderMailer.purchase(self).deliver_later end end I didn't change anything in the config files after updating: config/environments/development.rb config.action_mailer.default_url_options = { :host => 'http://localhost:3000' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = {:address => "localhost", :port => 1025} config.action_mailer.delivery_method = :letter_opener config/environments/production.rb Rails.application.routes.default_url_options[:host] = 'https://appnamegoeshere.herokuapp.com' config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = false config.action_mailer.default :charset => "utf-8" |
Rails reCAPTCHA with callback Posted: 02 Oct 2016 05:24 AM PDT I am trying to integrate a recaptcha into my website and I wanted to add some client side validation. I chose to use a gem to include the recaptcha tags, but I wanted to trigger a function once the recaptcha is checked. Looked through some google sites and found that a data-callback attribute with its value set to function name is all I need. I used recaptcha_tags helper from the gem to set it up and then a jquery method to add this data-callback attribute as I have not seed an option to do this inside the gem. $('.g-recaptcha').attr("data-callback", "myFunctionName"); After clicking the recaptcha the function is not called. Why? |
How to hook into Devise action before facebook redirect Posted: 02 Oct 2016 05:19 AM PDT I'm trying to hook into an action that will get called before devise users are redirected to facebook for login. The login link suggests I look into the passthru action in the omniauth_callbacks but that doesn't seem to work user_facebook_omniauth_authorize_path GET|POST /users/auth/facebook(.:format) my_devise/omniauth_callbacks#passthru Any ideas how to make a call before the redirect? Thanks! |
SimpleForm (DOB not displaying correctly) Posted: 02 Oct 2016 05:09 AM PDT For some reason SimpleForm is treating Date fields differently to other fields. This was the standard output after running the installs. You can see that the DOB (Date) is missing some elements I need to add: - add the col-sm-3 class
class="col-sm-3 control-label - Add a col-sm-9 div
<div class="col-sm-9"> GemFile gem 'bootstrap-sass' gem 'bootstrap-sass-extras' gem 'simple_form' _form.html.erb <%= simple_form_for @firm_info, html: { class: 'form-horizontal' }, wrapper: :horizontal_form, wrapper_mappings: { check_boxes: :horizontal_radio_and_checkboxes, radio_buttons: :horizontal_radio_and_checkboxes, file: :horizontal_file_input, boolean: :horizontal_boolean } do |f| %> <%= f.input :last_name %> <%= f.input :dob %> _form.html (result) <div class="form-group string optional firm_info_last_name"> <label class="col-sm-3 control-label string optional" for="firm_info_last_name">Last name</label> <div class="col-sm-9"> <input class="form-control string optional" name="firm_info[last_name]" id="firm_info_last_name" type="text"> </div> </div> <div class="form-group date optional firm_info_dob"> <label class="control-label date optional" for="firm_info_dob_1i">Dob</label> <div class="form-inline"> <select id="firm_info_dob_1i" name="firm_info[dob(1i)]" class="form-control date optional"> <option value="2011">2011</option> <option value="2012">2012</option> </select> <select id="firm_info_dob_2i" name="firm_info[dob(2i)]" class="form-control date optional"> <option value="1">January</option> <option value="2">February</option> </select> <select id="firm_info_dob_3i" name="firm_info[dob(3i)]" class="form-control date optional"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select> </div> </div> _form.html (what I want it to look like) <div class="form-group string optional firm_info_last_name"> <label class="col-sm-3 control-label string optional" for="firm_info_last_name">Last name</label> <div class="col-sm-9"> <input class="form-control string optional" name="firm_info[last_name]" id="firm_info_last_name" type="text"> </div> </div> <div class="form-group date optional firm_info_dob"> <label for="firm_info_dob_1i" class="**col-sm-3** control-label date optional">Dob</label> **<div class="col-sm-9">** <div class="form-inline"><select id="firm_info_dob_1i" name="firm_info[dob(1i)]" class="form-control date optional"> <option value="2011">2011</option> <option value="2012">2012</option> </select> <select id="firm_info_dob_2i" name="firm_info[dob(2i)]" class="form-control date optional"> <option value="1">January</option> <option value="2">February</option> </select> <select id="firm_info_dob_3i" name="firm_info[dob(3i)]" class="form-control date optional"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select> </div> </div> |
How do I use SendGrid's Inbound Parse Webhook example in Postman? Posted: 02 Oct 2016 04:16 AM PDT I am trying to figure out why incoming emails have paragraphs stripped in my Ruby on Rails app with Griddler and SendGrid. To do that I'd like to mock an inbound email using Postman. SendGrid have an example 'Default Payload' which looks like this: [Date] array(16) { ["headers"]=> string(1970) "Received: by mx0047p1mdw1.sendgrid.net with SMTP id 6WCVv7KAWn Wed, 27 Jul 2016 20:53:06 +0000 (UTC) Received: from mail-io0-f169.google.com (mail-io0-f169.google.com [209.85.223.169]) by mx0047p1mdw1.sendgrid.net (Postfix) with ESMTPS id AA9FFA817F2 for <parse@parse.yourdomain.com>; Wed, 27 Jul 2016 20:53:06 +0000 (UTC) Received: by mail-io0-f169.google.com with SMTP id b62so81593819iod.3 for <parse@parse.yourdomain.com>; Wed, 27 Jul 2016 13:53:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sendgrid.com; s=ga1; h=mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=GH5YTxjt6r4HoTa+94w6ZGQszFQSgegF+Jlv69YV76OLycJI4Gxdwfh6Wlqfez5yID 5dsWuqaVJZQyMq/Dy/c2gHSqVo60BKG56YrynYeSrMPy8abE/6/muPilYxDoPoEyIr/c UXH5rhOKjmJ7nICKu1o99Tfl0cXyCskE7ERW0= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=Sq6LVHbmywBdt3sTBn19U8VOmelfoJltz8IcnvcETZsYwk96RBxN+RKMN5fOZSKw4j 15HrgdIFfyDmp67YK0ygvOITlTvZ6XY5I0PtnvDtAQt79kS3tKjI3QKJoEp/ZjIjSzlL KG7agl6cxFgBbIN0yHWBOvy3O+ZXY8tZdom1yOvULjmjW1U9JkdOs+aJ6zq4qhZX/RM/ tIgLB461eJ5V95iQDDc5Ibj9Cvy4vJfXLQRO0nLVQAT2Yz58tkEO1bDZpWOPAyUNneIL yhIWp+SpbuqhMA68mq0krG1PjmWalUbpVcGJIGuOKB9mQFFo/MqdrUCjvYnyo1jPLPeX psdQ== X-Gm-Message-State: AEkoousvdxmDoxLlTUYJ1AOmCGJv77xRBBlfKv6YrthH0M2NueMwlOxUD6t8nidE9uonXbdJ/DQy/chmHUnN//a4 X-Received: by 10.107.6.101 with SMTP id 98mr38024553iog.41.1469652785829; Wed, 27 Jul 2016 13:53:05 -0700 (PDT) MIME-Version: 1.0 Received: by 10.107.48.17 with HTTP; Wed, 27 Jul 2016 13:53:05 -0700 (PDT) From: Sender Name <example@example.com> Date: Wed, 27 Jul 2016 14:53:05 -0600 Message-ID: <CAN_P_JMvV7ZpAQhOnDienypLrJmuhN=LQWweu4yScw4jQyXY2w@mail.gmail.com> Subject: Different File Types To: parse@parse.yourdomain.com Content-Type: multipart/mixed; boundary=001a113f8ad03e85160538a4343c " ["dkim"]=> string(22) "{@sendgrid.com : pass}" ["content-ids"]=> string(37) "{"ii_1562e2169c132d83":"attachment1"}" ["to"]=> string(26) "parse@parse.yourdomain.com" ["html"]=> string(479) "<div dir="ltr">Here's an email with multiple attachments<div><br></div><div><img src="cid:ii_1562e2169c132d83" alt="Inline image 1" width="455" height="544"><br clear="all"><div><br></div>-- <br><div class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><img src="https://sendgrid.com/brand/sg-logo-email.png" width="96" height="17"><br><div><br></div></div></div> </div></div> " ["from"]=> string(33) "Sender Name <example@example.com>" ["text"]=> string(139) "Here's an email with multiple attachments " ["sender_ip"]=> string(14) "209.85.223.169" ["spam_report"]=> string(844) "Spam detection software, running on the system "mx0047p1mdw1.sendgrid.net", has identified this incoming email as possible spam. The original message has been attached to this so you can view it (if it isn't spam) or label similar future email. If you have any questions, see @@CONTACT_ADDRESS@@ for details. Content preview: Here's an email with multiple attachments [image: Inline image 1] -- [...] Content analysis details: (2.6 points, 5.0 required) pts rule name description ---- ---------------------- -------------------------------------------------- 0.8 HTML_IMAGE_RATIO_02 BODY: HTML has a low ratio of text to image area 0.0 HTML_MESSAGE BODY: HTML included in message 1.8 HTML_IMAGE_ONLY_08 BODY: HTML: images with 400-800 bytes of words 0.0 T_MIME_NO_TEXT No text body parts " ["envelope"]=> string(66) "{"to":["parse@parse.yourdomain.com"],"from":"example@example.com"}" ["attachments"]=> string(1) "2" ["subject"]=> string(20) "Different File Types" ["spam_score"]=> string(5) "2.597" ["attachment-info"]=> string(287) "{"attachment2":{"filename":"DockMcWordface.docx","name":"DockMcWordface.docx","type":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},"attachment1":{"filename":"MG_2359.jpg","name":"_MG_2359.jpg","type":"image/jpeg","content-id":"ii_1562e2169c132d83"}}" ["charsets"]=> string(77) "{"to":"UTF-8","html":"UTF-8","subject":"UTF-8","from":"UTF-8","text":"UTF-8"}" ["SPF"]=> string(4) "pass" } My problem is I don't really understand how to put this format into Postman as Postman has no way to specify a raw payload like this. Alternatively, could I use curl to achieve something similar? |
Thinking sphinx doesn't start - “Failed to start searchd daemon” Posted: 02 Oct 2016 03:58 AM PDT rake ts:start gives following error: Failed to start searchd daemon. Check /home/deploy/megratec/shared/log/production.searchd.log. Failed to start searchd. Check the log files for more information. Log contains: [Sun Oct 2 13:35:38.507 2016] [ 4780] listening on 127.0.0.1:9306 [Sun Oct 2 13:35:38.507 2016] [ 4780] bind() failed on 127.0.0.1, retrying... ... [Sun Oct 2 13:36:14.541 2016] [ 4780] FATAL: bind() failed on 127.0.0.1: Address already in use [Sun Oct 2 13:36:14.543 2016] [ 4779] watchdog: main process 4780 exited cleanly (exit code 1), shutting down ps -efa shows no searchd running. SOS! Thanks :) |
Rendering barcode using Barby generator and WickedPDF Posted: 02 Oct 2016 05:31 AM PDT I'm trying to render a Barcode on the show action using Barby on a PDF, but it's not showing the barcode in visual aspects. new_barcode_pdf is active and returns: 4000000000297 The code i'm using in my controller: @barcode = Barcode.find(params[:id]).barcode_number @new_barcode_pdf = Barby::EAN13.new(@barcode) @barcode_pdf = Barby::HtmlOutputter.new(@new_barcode_pdf) @new_barcode_pdf.to_html respond_to do |format| format.html format.pdf do render :pdf => "pdf layout", :layout => 'show.pdf.erb', encoding: 'utf8' end end And in my view: <%= @new_barcode_pdf.to_html.html_safe %> I'm using WickedPdf to render the barcode. Thanks in advance, K. |
can submit a form many time with the same csrf token Posted: 02 Oct 2016 07:36 AM PDT In my application, I have a form for creating a City. Everything works fine when the remote option on the form is set to false. However, there is a problem when I change it to true. When the form is submitted remotely, I can submit two forms with the same CSRF token and instead of getting the ActionController::InvalidAuthenticityToken error for the second request. The second requests would also create an object, which must not happen. Do you know what causes this problem and how can I fix it? <%= form_for [:administrators,@city],remote: true,:authenticity_token => true do |f| %> <div class="field"> <%= f.label :province_id,'Select a province' %> <%= f.select :province_id,options_from_collection_for_select(Province.all, :id,:name, @city.province_id),{ :prompt => 'Select province' } %> <br> <div class="errors alert-box alert" style="display:none;"></div> </div> <div class="field"> <%= f.label :name %> <%= f.text_field :name%> <div class="errors alert-box alert" style="display:none;"></div> </div> <div class="action"> <% if @city.id? %> <%= f.submit 'Update', class:'button' %> <btn class='cancel_form_button button tiny alert'> </btn> <% else %> <%= f.submit 'Create', class:'button' %> <% end %> </div> |
How to start a web application with ROR Posted: 02 Oct 2016 03:35 AM PDT I'm about to build a web application like Wetransfer with Ruby on Rails. I need to know how to start it?. I've a good basics of Ruby language and Rails framework which I learned from teamtreehouse. My question is Do I need to start it from scratch or there's a template or CMS I can use to build on it? And if I'm going from scratch how can I plan to build it? it might look like a noob question, but everyone has a start, right . |
Rails devise how to make admin account access users account Posted: 02 Oct 2016 02:47 AM PDT I want to make admin account access the user account. Also i am having results section in my webapp for which only admin should have write access and normal users should have read access. I can set master password for logging in to users account(solves admin login problem). For managing results section access i am using cancan gem. But the problem is how to restrict normal users from editing results section (like if logged in with master password user.admin? should have to be true in cancan gem). if user.admin? can :manage, :all else can :read, :all end How can i achieve this? |
PDFKIT hangs while generating PDF in controller but not in console Posted: 02 Oct 2016 01:56 AM PDT I'm having issues while trying to generate PDFs using PDFKit. If issue the following commands on console: kit = PDFKit.new("http://localhost:3000/invoices/57f0bf61fc7b3415fc000000") followed by kit.to_file("pdfs/invoices/57f0bf61fc7b3415fc000000.pdf") Everything works fine and the file is generated. Now if I have the same code in a controller, the pdf generation hangs on step 1 and no error is displayed. If I try wkhtmltopdf http://localhost:3000/invoices/ivoice_id invoice.pdf it also works. Why is that? More importantly, how to fix it? I'm using Rails 4. |
Why Rails 4 stopped compiling CSS while in development Posted: 02 Oct 2016 01:34 AM PDT I have a Rails App that's mostly an API however I do need to render an invoice. So for this particular Model, I've got a view which renders a simple page. When I added the page, the layout and the style, everything was working fine. Now suddenly the CSS is no longer rendering and I can't see why. On the browser I get the error: http://localhost/assets/model.self-19a187bec6cdb96d6de80a61c16c857c613536adf9138476bd367db38d282635.js?body=1 and many others in a similar fashion. How can I solve this? |
Rails 4 Server sent events Posted: 02 Oct 2016 01:51 AM PDT How in Rails 4 using Server Sent Events and listen multiple callbakcs (create and destroy)? For example, Model: class Job < ActiveRecord::Base after_create :notify_job_created after_destroy :notify_job_destroyed def self.on_create Job.connection.execute "LISTEN create_jobs" loop do Job.connection.raw_connection.wait_for_notify do |event, pid, job| yield job end end ensure Job.connection.execute "UNLISTEN create_jobs" end def self.on_destroy Job.connection.execute "LISTEN destroy_jobs" loop do Job.connection.raw_connection.wait_for_notify do |event, pid, job| yield job end end ensure Job.connection.execute "UNLISTEN destroy_jobs" end def notify_job_created Job.connection.execute "NOTIFY create_jobs, '#{self.id}'" end def notify_job_destroyed Job.connection.execute "NOTIFY destroy_jobs, '#{self.id}'" end end Controller: class StreamJobsController < ApplicationController include ActionController::Live def index_stream response.headers['Content-Type'] = 'text/event-stream' sse = SSE.new response.stream begin Job.on_create do |id| job = Job.find(id) stand = Stand.find(job.stand_id) t = render_to_string( partial: 'projects/stand', formats: [:html], locals: {stand: stand} ) sse.write(t, event: 'create') end Job.on_destroy do |id| job = Job.find(id) sse.write(job.stand_id, event: 'destroy') end rescue IOError # When the client disconnects, we'll get an IOError on write ensure sse.close end end end JS code: $(function () { var source = new EventSource('/jobs_stream'); source.addEventListener('create', function(e){ console.log('Create stand:', e.data); $("table.project-stands.table.table-condensed").find("tbody#stand-list").prepend($.parseHTML(e.data)); }); source.addEventListener('destroy', function(e){ console.log('Destroy stand: ', e.data); var id = e.data; $("table.project-stands.table.table-condensed").find("tr#stand_" + id).remove(); }); source.addEventListener('finished', function(e){ console.log('Close:', e.data); source.close(); }); }); As result, I get only LISTEN create_jobs. What's wrong in my controller? Thanks |
How to terminate subscription to an actioncable channel from server? Posted: 02 Oct 2016 01:29 AM PDT Is there a way to terminate the subscription to a particular channel for any particular consumer from the server side (controller) so that disconnected callback in my coffee script file can be invoked? |
Rails: search form in boostrap navbar Posted: 02 Oct 2016 01:50 AM PDT I'm trying to add search form to bootstrap navbar with no luck. Search form works fine in app/views/searches/new.html.erb. When I add the same search form in app/views/layouts/_header.html.erb, I get 'First argument in form cannot contain nil or be empty' all the time. I tried to change @search in form to search paths, but none of them works properly. I'd appreciate any tips how to make the code better, I feel like I could've written the code in search model in more elegant way. Thank you for help. app/views/layouts/_header.html.erb <%= form_for @search, html: {class: "navbar-form navbar-left"} do |f| %> <div class="input-group searchbar"> <%= f.text_field :keywords, class: "form-control", placeholder: "Search" %> <span class="input-group-addon"> <%= button_tag(:class => "white") do %> <i class="glyphicon glyphicon-search"></i> <% end %> </span> </div> <% end %> search model def questions @questions = find_questions end def answers @answers = find_answers end def users @users = find_users end private def find_questions questions = Question.order(created_at: :desc) questions = questions.where("title like ? OR content like?", "%#{keywords}%", "%#{keywords}%") if keywords.present? questions end def find_answers answers = Answer.order(created_at: :desc) answers = answers.where("content like ?", "%#{keywords}%") if keywords.present? answers end def find_users users = User.order(:username) users = users.where("username like ?", "%#{keywords}%") if keywords.present? users end searches controller def new @search = Search.new end def create @search = Search.create!(allowed_params) redirect_to @search end def show @search = Search.find(params[:id]) end private def allowed_params params.require(:search).permit! end questions controller - I have the same code in answers and users controllers def index @questions = Question.all if params[:search] @questions = Question.search(params[:search]) end end routes searches GET /searches(.:format) searches#index POST /searches(.:format) searches#create new_search GET /searches/new(.:format) searches#new edit_search GET /searches/:id/edit(.:format) searches#edit search GET /searches/:id(.:format) searches#show PATCH /searches/:id(.:format) searches#update PUT /searches/:id(.:format) searches#update DELETE /searches/:id(.:format) searches#destroy root GET / home#index |
Transfer fund from stripe platform account to a recipient by email Posted: 02 Oct 2016 01:23 AM PDT One of my clients have a situation to pay their website user directly from platform account to user. I can do it by using their transfer payment API. But, my client want to pay to user's email so that user can have option to perform rest of the action. I went through their API documentation but don't see anything related to do that. Does anyone have similar experience or know anything related to do that? |
call instance method with class instance variable - ruby on rails Posted: 02 Oct 2016 01:35 AM PDT I'm trying to call an instance method (defined in model) from the instance variable in controller but could not get that work and server logs saying undefined method `active_users' for #< Admin controller @admin = Admin.first @admin.active_users Admin Model def self.active_users byebug end I know that we can call it through the class directly like Admin.active_users . Why is it not accessible by instance of the class? |
Inline C or C++ for ruby on rails Posted: 02 Oct 2016 01:09 AM PDT Does anyone know where I can find source code that uses RubyInline gem I can't figure out for the life of me how to use this gem. I haven't found documentation for a beginner on this subject. But I am on Cloud 9 and I just what to get some form of Inline C to work and go on exploring from there. |
How to use engine's gem in main application? Posted: 02 Oct 2016 01:01 AM PDT I am making a rails plugin named signup . In this plugin, I used bcrypt gem, Here is my engine.rb module Signup class Engine < ::Rails::Engine isolate_namespace Signup require 'rubygems' require 'bcrypt' end end My Gemfile: source 'https://rubygems.org' gemspec gem 'bcrypt' I follow this Rails Engine - Gems dependencies, how to load them into the application? But In my demo application, when start rails server, then I got this error: lib/signup/engine.rb:9:in `require': cannot load such file -- bcrypt (LoadError) I want to load bcrypt gem in my demo application. If I add gem 'bcrypt' in my demo application's Gemfile and run bundle install, it does not show any kind of error, But I don't want to do it. I want that gem 'bcrypt' will be load automatically in my demo application without adding this in Gemfile. |
Rails 5: cache user role info at login and flush it at logout Posted: 02 Oct 2016 01:01 AM PDT I'm trying to implement role info caching starting from login to logout. In my models/role.rb I have this: class Role < ApplicationRecord belongs_to :user, optional: true accepts_nested_attributes_for :user class << self def all_cached Rails.cache.fetch("roles") { Role.where(user_id: current_user) } end end private def flush_cache Rails.cache.delete('roles') end In my controllers/roles_controller.rb I have this: def roles @roles = Role.all_cached end In my controllers/sessions_controller.br I have this: class SessionsController < ApplicationController def new render :layout => "empty" end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in user params[:session][:remember_me] == '1' ? remember(user) : forget(user) redirect_back_or user else flash.now[:error] = 'Invalid email/password combination!' render 'new', :layout => "empty" end end def destroy log_out if logged_in? redirect_to login_path end end How do I set current_user role is cached at login and deleted at logout? I want to cache it once for the whole user session so I can retreive info at any time for checking user roles and permissions. I do not want to store this info in session as it is quite a lot of info + not sure if that is safe. |
Modal Not Saving or Populating Rails 4 Posted: 02 Oct 2016 12:38 AM PDT Im having an issue with my rails 4 bootstrap 3 modal, I have all the pieces in place (see below) but when I try to save the item I get the following error, Started POST "/clients" for ::1 at 2016-10-02 00:47:51 -0600 Processing by ClientsController#create as JS Parameters: {"utf8"=>"✓", "client"=>{"client_name"=>"TEST"}, "client_type"=>"Corporation", "commit"=>"Save"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]] (0.1ms) BEGIN (0.1ms) ROLLBACK Rendering clients/create.js.erb Rendered clients/create.js.erb (177.1ms) Completed 500 Internal Server Error in 191ms (ActiveRecord: 0.6ms) NoMethodError - undefined method `upcase' for nil:NilClass: app/views/clients/_client.html.erb:2:in `_app_views_clients__client_html_erb___167091429619630660_70125075671460' The upcase is working fine on all current items that were created before the modal was implemented. my table row '_client.html.erb' file: <tr id="client_<%= client.id %>"> <td class="vert-align"><center><%= client.client_ident.upcase %></center></td> <td class="vert-align"><center><%= client.client_name %></center></td> <td class="vert-align visible-sm visible-md visible-lg"><center><%= time_ago_in_words(client.created_at) %></center></td> <td class="vert-align visible-xs"><center> <%= link_to client_path(client), :class => 'btn btn-default btn-sm' do %> <i class="fa fa-eye" aria-hidden="true"></i> <% end %> </center></td> <td class="vert-align visible-xs"><center> <%= link_to edit_client_path(client), :class => 'btn btn-default btn-sm' do %> <i class="fa fa-pencil" aria-hidden="true"></i> <% end %> </center></td> <td class="vert-align visible-xs"><center> <%= link_to client_path(client), :class => 'btn btn-default btn-sm', method: :destroy do %> <i class="fa fa-trash" aria-hidden="true"></i> <% end %> </center></td> <td class="visible-sm visible-md visible-lg vert-align"><center><%= link_to "View", client_path(client), :class => 'btn btn-default btn-sm' %></center></td> <td class="visible-sm visible-md visible-lg vert-align"><center><%= link_to "Edit", edit_client_path(client), :class => 'btn btn-default btn-sm' %></center></td> <td class="visible-sm visible-md visible-lg vert-align"><center><%= link_to "Remove", client_path(client), method: :destroy, :class => 'btn btn-default btn-sm' %></center></td> </tr> my 'index.html.erb': <div class="row"> <div class="col-xs-12"> <table class="table table-condensed table-striped"> <thead> <tr> <th><center><%= sort_link(@q, :client_ident, 'ID') %></center></th> <th><center><%= sort_link(@q, :client_name, 'Name', default_order: :asc) %></center></th> <th class="vert-align visible-sm visible-md visible-lg"><center><%= sort_link(@q, :created_at, 'Client For') %></center></th> <th colspan="3"><center></center></th> </tr> </thead> <tbody id="client-row"> <% @clients.each do |client| %> <%= render partial: client %> <% end %> </tbody> </table> <%= paginate @clients %> </div> </div> <%= render partial: 'clients/create_modal' %> my create_modal.html.erb file: <div class="modal fade" id="newClient" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel"><text class="pv-green">PATROL</text><text class="pv-gray">VAULT</text></h4> </div> <%= form_for(@client, remote: :true) do |f| %> <div class="modal-body"> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="field"> <%= f.label :client_name, "Client Name" %><br /> <%= f.text_field :client_name, :class => 'form-control client_name' %> </div> </div> <div class="col-xs-12 col-sm-6"> <%= f.label :client_type, "Type" %><br /> <%= select_tag :client_type, options_for_select([['Corportation' ,'Corporation'], ['Individual', 'Individual']]), :class => 'form-control' %> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <%= f.submit "Save", :class => 'btn btn-primary' %> </div> <% end %> </div> </div> </div> and finally my create.js.erb file $('#newClient').modal('hide'); $('.client_name').val(''); $('.client_type').val(''); $('#client-row').prepend('<%= j render @client %>'); $('#client_<%= client.id %>').hide().fadeIn(2000); Not sure where I am going wring, any assistance would be greatly appreciated. EDIT #1 - Client_Ident callback # client.rb before_create :assign_client_ident def assign_client_ident begin self.client_ident = SecureRandom.hex(2).upcase other_client = Client.find_by(client_ident: self.client_ident) end while other_client end EDIT # 2 Clients Controller and Model #clients_controller.rb class ClientsController < ApplicationController before_action :set_client, only: [:show, :edit, :update, :destroy] # GET /clients # GET /clients.json def index @q = Client.ransack(params[:q]) @clients = @q.result(distinct: true).page(params[:page]).per(5) @client = Client.new end # GET /clients/1 # GET /clients/1.json def show @client = Client.find(params[:id]) @sites = @client.sites end # GET /clients/new def new @client = Client.new end # GET /clients/1/edit def edit end # POST /clients # POST /clients.json def create @client = Client.new(client_params) respond_to do |format| if @client.save format.html { redirect_to @client, notice: 'Client was successfully created.' } format.json { render :show, status: :created, location: @client } format.js else format.html { render :new } format.json { render json: @client.errors, status: :unprocessable_entity } format.js end end end # PATCH/PUT /clients/1 # PATCH/PUT /clients/1.json def update respond_to do |format| if @client.update(client_params) format.html { redirect_to @client, notice: 'Client was successfully updated.' } format.json { render :show, status: :ok, location: @client } else format.html { render :edit } format.json { render json: @client.errors, status: :unprocessable_entity } end end end # DELETE /clients/1 # DELETE /clients/1.json def destroy @client.destroy respond_to do |format| format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_client @client = Client.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def client_params params.require(:client).permit(:client_ident, :client_name, :client_type) end end # Client Model class Client < ApplicationRecord # Before Actions before_create :assign_client_ident # Relationships has_many :sites, dependent: :destroy # Validations validates :client_name, :client_type, presence: true # Custom Methods def assign_client_ident begin self.client_ident = SecureRandom.hex(2).upcase other_client = Client.find_by(client_ident: self.client_ident) end while other_client end end |
Conditionally Saving has_many_through Relationships Posted: 02 Oct 2016 01:24 AM PDT In Rails, how would one conditionally associated records on a has_many_through relationship? Using the following Rails docs example: class Physician < ApplicationRecord has_many :appointments has_many :patients, through: :appointments end class Appointment < ApplicationRecord belongs_to :physician belongs_to :patient end class Patient < ApplicationRecord has_many :appointments has_many :physicians, through: :appointments end Suppose I wanted to have an appointment reference exactly two physicians. That is, there will not be any appointment record one there is less than two physicians assigned. However, how could that appointment then reference each physician? Example Basically, I want to keep track of users liking other users and mutual likes between them. A connection is established when both users like each other. But I don't want a connection when only one user likes another but it is not reciprocal. When User A likes User B. A "like" is created. When User B likes User A. A "like" is created. A "connection" is also created. The connection should be able to call: connection.users The user should be able to call: user.likes user.connections The problem that I'm having is how can that relationship table know when it is mutual? |
ActionMailer Template stored in DB Posted: 02 Oct 2016 12:10 AM PDT The question here is "Is it bad practice to store email templates in DB and render?" I know this is what people don't apply. (Usually it's rendered from .erb and good to go, and it should be avoided from accessing DB as much as possible.) But there are business requirements below - For business reasons, I need to have the history of each email. (Who's got sent, what title and bodies are sent.)
Third party Transaction Email service provider can store the histories, but I need to store them locally. So I'm thinking about storing templates within DB, and render it, so that I can track what email was sent even templates change. Any advices for that? |
Polymorphic relationship confusion Posted: 01 Oct 2016 11:31 PM PDT So I'm confused about how ActiveRecord is handling this, and hoped someone could give me some insight. I have a table that has a polymorphic relationship. We'll call it table choices. In there I have defined: belongs_to :chooseable, polymorphic: true I have two models, let's call one movies, and the other plays. In there, I have: has_many :choices as: chooseable, dependent: destroy In the model with the polymorphic relationship I have two scopes: scope :with_movies, -> { includes(:movies) .where("chooseable_type": "Measure") } scope :with_shows, -> { includes(:shows) .where(shows: { hidden: false }) } What is confusing to me, is, if I say users.choices.with_movies, and I leave out the chooseable_type where condition, AR balks at me and says: Unknown column 'choices.chooseable_type' in 'where clause': SELECT `movies`.* FROM `movies` WHERE `choices`.`chooseable_type` = 'Movie' AND `movies`.`id` IN (728) Yet, in the second scope with_shows, I don't need to define chooseable_type - it works fine. The even more confusing thing is, if I remove the where clause, with_shows, doesn't work as well. I really don't understand why the where clause in the second scope allows a proper query to be generated, yet without it, it falls on its face. |
No comments:
Post a Comment