Friday, December 16, 2016

Rails Pundit allow published content to be viewed by others while preventing others from viewing user's info | Fixed issues

Rails Pundit allow published content to be viewed by others while preventing others from viewing user's info | Fixed issues


Rails Pundit allow published content to be viewed by others while preventing others from viewing user's info

Posted: 16 Dec 2016 08:10 AM PST

Okay, so I have a User, Book and Chapter entities in my system.

If an author (User entity) publishes a book as well as a chapter, then it's available for the public to see. Let's call author Jim.

That means if another normal user, named Tycus, wants to read Jim's book and book chapters, he should be able to do so.

I am using Pundit gem (https://github.com/elabs/pundit) for permissions.

The problem I am facing is, when Tycus tries to access Jim's book, it appears my Rails is trying to fetch linked relationships (chapter --> book --> author) along with it:

Started GET "//books/16" for ::1 at 2016-12-16 23:29:38 +0800  Processing by BooksController#show as JSON    Parameters: {"id"=>"16"}    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 21], ["LIMIT", 1]]    Book Load (0.1ms)  SELECT  "books".* FROM "books" WHERE "books"."id" = ? LIMIT ?  [["id", 16], ["LIMIT", 1]]    Role Load (0.1ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]  [active_model_serializers]   User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]  [active_model_serializers]   Chapter Load (0.1ms)  SELECT "chapters".* FROM "chapters" WHERE "chapters"."book_id" = ?  [["book_id", 16]]  [active_model_serializers]   Genre Load (0.1ms)  SELECT "genres".* FROM "genres" INNER JOIN "books_genres" ON "genres"."id" = "books_genres"."genre_id" WHERE "books_genres"."book_id" = ?  [["book_id", 16]]  [active_model_serializers]   Love Load (0.1ms)  SELECT "loves".* FROM "loves" WHERE "loves"."book_id" = ?  [["book_id", 16]]  [active_model_serializers] Rendered BookSerializer with ActiveModelSerializers::Adapter::JsonApi (30.04ms)  Completed 200 OK in 48ms (Views: 29.6ms | ActiveRecord: 2.0ms)      Started GET "//chapters/5" for ::1 at 2016-12-16 23:29:38 +0800  Processing by ChaptersController#show as JSON    Parameters: {"id"=>"5"}    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 21], ["LIMIT", 1]]    Chapter Load (0.1ms)  SELECT  "chapters".* FROM "chapters" WHERE "chapters"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]    Book Load (0.1ms)  SELECT  "books".* FROM "books" WHERE "books"."id" = ? LIMIT ?  [["id", 16], ["LIMIT", 1]]  Started GET "//chapters/7" for ::1 at 2016-12-16 23:29:38 +0800  Started GET "//chapters/6" for ::1 at 2016-12-16 23:29:38 +0800  [active_model_serializers]   User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]  Processing by ChaptersController#show as JSON  Processing by ChaptersController#show as JSON  Started GET "//users/2" for ::1 at 2016-12-16 23:29:38 +0800  [active_model_serializers] Rendered ChapterSerializer with ActiveModelSerializers::Adapter::JsonApi (10.73ms)    Parameters: {"id"=>"7"}    Parameters: {"id"=>"6"}  Processing by UsersController#show as JSON  Completed 200 OK in 24ms (Views: 14.2ms | ActiveRecord: 0.9ms)        User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 21], ["LIMIT", 1]]    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 21], ["LIMIT", 1]]    Parameters: {"id"=>"2"}    Chapter Load (0.2ms)  SELECT  "chapters".* FROM "chapters" WHERE "chapters"."id" = ? LIMIT ?  [["id", 7], ["LIMIT", 1]]    Chapter Load (0.2ms)  SELECT  "chapters".* FROM "chapters" WHERE "chapters"."id" = ? LIMIT ?  [["id", 6], ["LIMIT", 1]]    User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 21], ["LIMIT", 1]]    Book Load (0.1ms)  SELECT  "books".* FROM "books" WHERE "books"."id" = ? LIMIT ?  [["id", 16], ["LIMIT", 1]]    Book Load (0.1ms)  SELECT  "books".* FROM "books" WHERE "books"."id" = ? LIMIT ?  [["id", 16], ["LIMIT", 1]]    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]  [active_model_serializers]   User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]  [active_model_serializers]   User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]    Role Load (0.2ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]  [active_model_serializers] Rendered ChapterSerializer with ActiveModelSerializers::Adapter::JsonApi (6.75ms)  [active_model_serializers] Rendered ChapterSerializer with ActiveModelSerializers::Adapter::JsonApi (5.92ms)  Completed 403 Forbidden in 16ms (ActiveRecord: 1.0ms)      Completed 200 OK in 22ms (Views: 9.9ms | ActiveRecord: 1.6ms)      Completed 200 OK in 20ms (Views: 7.9ms | ActiveRecord: 1.0ms)        Pundit::NotAuthorizedError (not allowed to show? this #<User id: 2, first_name: "James", last_name: "Raynor", username: "Jimmy", email: "chewedon+jim@gmail.com", password_digest: "$2a$10$9xCQKiku7YD.xjzbj34/P.4JUHCOf4lKXbVeqKy2PNb...", banned: false, role_id: 3, created_at: "2016-12-01 13:56:30", updated_at: "2016-12-11 08:31:42", photo: "jim_raynor.jpg", email_confirmed: true, confirm_token: nil, password_reset_token: nil>):    app/controllers/users_controller.rb:33:in `show'  

As a result, Pundit is raising a Pundit::NotAuthorizedError because somehow it thinks I'm trying to access the user's information.

My Emberjs frontend rightfully resonate with this exception raised:

Ember error

My Chapter_Controller certainly don't explicitly ask for the author's info:

def show    chapter = Chapter.find_by(id: params[:id])      if chapter.present?      authorize chapter      render json: chapter    else      skip_authorization      render status: :not_found    end  end  

I can fix this error by modify my User policy show? method to return true:

def show?      true  end  

But this then exposes my user's information to anyone to see. For example, let's say an author does not want to disclose their real name, only their username (maybe the author isn't too confident his/her book will sell well, so using an alias username to hide their identity).

By specifying true in my User policy show method, any logged in user can make a GET request to: http://localhost:3000/users/{author_id} and see the author's details.

So my question is - is there a way to allow other user to view book and book chapters of an author but at the same time do not allow other users to view the author's personal info?

Update

It appears my active model serializer is the one trying to pull the user record.

I think a similar discussion is happening on the active model serializer github pages: https://github.com/rails-api/active_model_serializers/issues/1552

Rails: Validating JSON request format before API controller methods

Posted: 16 Dec 2016 07:41 AM PST

I've built a rails API that receives JSON. I want to validate that the request body is valid JSON and provide a valid error on the API response if not. Spent quite a lot of time trying different options and trying to find an answer but no success.

Whatever I do to try and catch the error, it always throws the following error when I send some incorrect test JSON.

JSON::ParserError at /api/v1/apikey123    743: unexpected token at '{      "query": "hi there" (missing comma here on purpose)      "lang": "en",      "sessionId": "en" }  

json (2.0.2) lib/json/common.rb, line 156    ``` ruby  151     #   additions even if a matching class and create_id was found. This option  152     #   defaults to false.  153     # * *object_class*: Defaults to Hash  154     # * *array_class*: Defaults to Array  155     def parse(source, opts = {})  > 156       Parser.new(source, opts).parse    157     end  158     159     # Parse the JSON document _source_ into a Ruby data structure and return it.  160     # The bang version of the parse method defaults to the more dangerous values  161     # for the _opts_ hash, so be sure only to parse trusted _source_ documents.  

Here is my code:

module Api    class ApiController < ApplicationController      protect_from_forgery with: :null_session      before_action :authenticate, :parse_request        private      def parse_request        begin          @user_input = JSON.parse(request.body.read)        rescue JSON::ParserError => e           return false        end      end        ...      end  end  

I'd like to know how to handle this without throwing an error and send back a response that has an error message with "Invalid JSON format"

Getting value of attribute and testing it with Nokogiri

Posted: 16 Dec 2016 07:54 AM PST

I have an XML dump and am trying to parse it with Nokogiri to get a text value of an attribute, then find out if it matches a certain string I'm looking for. Here is a snippet of my XML file:

      #(Element:0x3fc58cc091f8 {        name = "host",        attributes = [ #(Attr:0x3fc58cc08528 { name = "starttime", value = "1481896934" }), #(Attr:0x3fc58cc08514 { name = "endtime", value = "1481896947" })],        children = [          #(Element:0x3fc58af6bdc0 {            name = "status",            attributes = [              #(Attr:0x3fc58af6b6f4 { name = "state", value = "up" }),              #(Attr:0x3fc58af6b6e0 { name = "reason", value = "arp-response" }),              #(Attr:0x3fc58af6b6cc { name = "reason_ttl", value = "0" })]            }),          #(Text "\n"),          #(Element:0x3fc58a744fe8 {            name = "os",            children = [              #(Element:0x3fc58c1392f0 {                name = "osmatch",                attributes = [                  #(Attr:0x3fc58c1381d4 { name = "name", value = "Microsoft Windows XP SP2 or SP3, or Windows Server 2003" }),                  #(Attr:0x3fc58c1381c0 { name = "accuracy", value = "100" }),                  #(Attr:0x3fc58c1381ac { name = "line", value = "57766" })],                children = [                  #(Text "\n"),                  #(Element:0x3fc58ae89e70 {                    name = "osclass",                    attributes = [                      #(Attr:0x3fc58ae893bc { name = "type", value = "general purpose" }),                      #(Attr:0x3fc58ae893a8 { name = "vendor", value = "Microsoft" }),                      #(Attr:0x3fc58ae89394 { name = "osfamily", value = "Windows" }),                      #(Attr:0x3fc58ae89380 { name = "osgen", value = "XP" }),                      #(Attr:0x3fc58ae8936c { name = "accuracy", value = "100" })],                    children = [ #(Element:0x3fc58b19428c { name = "cpe", children = [ #(Text "cpe:/o:microsoft:windows_xp")] })]                    }),                  #(Text "\n"),  

So, what I'm trying to do is get the contents of os/osmatch/@name.value. In this case it would be Windows XP SP2 or SP3, or Windows Server 2003.

I've got that part down:

 doc.xpath("//host").each do |host|     os = host.at_xpath("os/osmatch").at_xpath("@name").value rescue nil   end     output: Microsoft Windows XP SP2 or SP3, or Windows Server 2003  

Typically, my XML file will have tons of hosts with different OSes though, so the output will likely look something like:

 Microsoft Windows XP SP2 or SP3, or Windows Server 2003   Ubuntu 14.04 Linux   Microsoft Windows 7, or Microsoft Windows 8   FreeBSD X.X.X   ....  

What I'm trying to do is match certain strings to the values I'm looking for now, so I can do some action if Windows XP is found for instance.

 doc.xpath("//host").each do |host|     os = host.at_xpath("os/osmatch").at_xpath("@name[contains(value, 'Windows XP')]")   end  

But instead, I'm getting an error, so I know I'm doing something wrong. I've tried some other variations, but can't figure out how to do it:

 Nokogiri::XML::XPath::SyntaxError: Invalid expression: @name[contains(value, 'Windows']  

adding a new column **attachment** in existing table in ruby on rails

Posted: 16 Dec 2016 07:55 AM PST

Ok So I have a simple rails application called ticket. here I create ticket and store into database. I generated it using scaffold.

It has 5 columns. ( I generated it using scaffold)   Name   Seat id seq   Address   Price paid   Email Address  

And the application is working fine. I can create , edit, and update the ticket. I am much interested in creating the ticket rather than editing and deleting.

Now I want to add a new column in the database named attachment where a person can upload word, pdf files. I have seen many tutorials but none is explaining how I can incorporate into an existing table which already have some fields.

tickets_controller.rb

  class TicketsController < ApplicationController    before_action :set_ticket, only: [:show, :edit, :update, :destroy]      def index      @tickets = Ticket.all    end      def show    end      def new      @ticket = Ticket.new    end      def edit    end      def create      @ticket = Ticket.new(ticket_params)        respond_to do |format|        if @ticket.save          format.html { redirect_to @ticket, notice: 'Ticket was successfully created.' }          format.json { render :show, status: :created, location: @ticket }    else          format.html { render :new }          format.json { render json: @ticket.errors, status: :unprocessable_entity }        end      end    end        def update      respond_to do |format|        if @ticket.update(ticket_params)          format.html { redirect_to @ticket, notice: 'Ticket was successfully updated.' }          format.json { render :show, status: :ok, location: @ticket }        else          format.html { render :edit }          format.json { render json: @ticket.errors, status: :unprocessable_entity }        end      end    end        def destroy      @ticket.destroy      respond_to do |format|        format.html { redirect_to tickets_url, notice: 'Ticket was successfully destroyed.' }        format.json { head :no_content }      end    end      private        def set_ticket        @ticket = Ticket.find(params[:id])      end          def ticket_params        params.require(:ticket).permit(:name, :seat_id_seq, :address, :price_paid, :email_address)      end  end  

tickets Model

class Ticket < ApplicationRecord  end  

_form.html.erb

<%= form_for(ticket) do |f| %>    <% if ticket.errors.any? %>    <div id="error_explanation">      <h2><%= pluralize(ticket.errors.count, "error") %> prohibited this    ticket from being saved:</h2>        <ul>      <% ticket.errors.full_messages.each do |message| %>        <li><%= message %></li>      <% end %>      </ul>    </div>  <% end %>    <div class="field">    <%= f.label :name %>    <%= f.text_field :name %>  </div>    <div class="field">    <%= f.label :seat_id_seq %>    <%= f.text_field :seat_id_seq %>  </div>    <div class="field">    <%= f.label :address %>    <%= f.text_area :address %>  </div>    <div class="field">    <%= f.label :price_paid %>    <%= f.text_field :price_paid %>  </div>    <div class="field">    <%= f.label :email_address %>    <%= f.text_field :email_address %>  </div>    <div class="actions">    <%= f.submit %>  </div>  <% end %>  

new.html.erb

<h1>New Ticket</h1>    <%= render 'form', ticket: @ticket %>    <%= link_to 'Back', tickets_path %>  

I found some on some of the sources that to upload a document we need to create a table with three columns ( filename, content_type, data) , and I thought to add these column into the existing tickets table, but then I don't know what chnages i need to make in the new.html.erb file. On this file i am loading the form where you can enter the information, and I want to show a field to upload a file on this page.

ruby -v : 2.2.6p396 rails -v : 5.0.0.1 ( Please reply in way that I can use the solution on the rails 4.0 too)

Check if email confirmation was sent is functional or integration test?

Posted: 16 Dec 2016 07:08 AM PST

I covering my controllers with uTesting using standard Minitest.

After a new user create his account, the app sends the confirmation email (aka "click here to activate your account).

IMHO, this should be a funcional test (im covering controller basic behavior). And then i should create an Integration test combining User controller and Mailer.

But reviewing rails guide (http://guides.rubyonrails.org/testing.html), the example made me confused: they do functional test inheriting from ActionDispatch::IntegrationTest, instead ActionController::TestCase.

What is the best approach?

Get the polymorphic edit path of the parent rather than the child

Posted: 16 Dec 2016 06:26 AM PST

so I'm working on a project and as part of it I've had to separate a model into a number of sub classes these subclasses are basically just empty wrappers around the parent class.

This problem I'm having is that previously the edit url for these records was retrieved using polymorphic_path, this now breaks because it's looking for the url of the child class rather than the parent class. Is there anyway to get polymorphic_path to return the parent classes URL?

Any help would be greatly appreciated.

How to select all records having an attachment?

Posted: 16 Dec 2016 07:25 AM PST

I'm using rails4 with paperclip. On one of my forms I would like to list only the records of a resource having a paperclips attachment. Is there any built in support for this in paperclip?

Ruby Gem Installation error - > gem install json -v '1.6.5'

Posted: 16 Dec 2016 06:15 AM PST

I am trying to install gem json (version 1.6.5) in Windows 7. Below are my ruby and gem version.

> ruby -v  ruby 1.9.3p286 (2012-10-12) [i386-mingw32]  > gem -v 1.8.24  

I have Devkit installed.

Below is the output I am getting:

    > gem install json -v '1.6.5'  Temporarily enhancing PATH to include DevKit...  Building native extensions.  This could take a while...  ERROR:  Error installing json:          ERROR: Failed to build gem native extension.            C:/Ruby187/bin/ruby.exe extconf.rb  creating Makefile    make  gcc -I. -I/C/Ruby187/lib/ruby/1.8/i386-mingw32 -I/C/Ruby187/lib/ruby/1.8/i386-mi  ngw32 -I.   -g -O3 -DFD_SETSIZE=256   -Wall  -c parser.c  ../fbuffer/fbuffer.h:129:13: warning: 'fbuffer_append_long' defined but not used    ../fbuffer/fbuffer.h:136:17: warning: 'fbuffer_dup' defined but not used  ../fbuffer/fbuffer.h:149:14: warning: 'fbuffer_to_s' defined but not used  ../fbuffer/fbuffer.h:90:13: warning: 'fbuffer_append_str' defined but not used  gcc -shared -s -o parser.so parser.o -L. -LC:/Ruby187/lib -L.  -Wl,--enable-auto  -image-base,--enable-auto-import,--export-all   -lmsvcrt-ruby18  -lshell32 -lws2  _32    make install  install -d C:/Ruby187/lib/ruby/gems/1.8/gems/json-1.6.5/ext/json/ext/json/ext  make: execvp: install: Permission denied  make: *** [C:/Ruby187/lib/ruby/gems/1.8/gems/json-1.6.5/ext/json/ext/json/ext] E  rror 127      Gem files will remain installed in C:/Ruby187/lib/ruby/gems/1.8/gems/json-1.6.5  for inspection.  Results logged to C:/Ruby187/lib/ruby/gems/1.8/gems/json-1.6.5/ext/json/ext/pars  er/gem_make.out  

unable send pdf attachment in email generated from wicked-pdf in rails?

Posted: 16 Dec 2016 07:32 AM PST

I am trying to send the pdf as an attachment in the email. but getting an error.

ctionView::MissingTemplate at /invoises/BRUqWOeEVNSN6GCwxQqLGg%253D%253D/send_invoice_email Missing template invoises/#{invoise.id}/show_pdf_invoice.pdf.erb with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :m

i am using wicked_pdf gem.trying to generate the pdf from html view

method in controller

  def send_invoice_email      CompanyMailer.invoice(@invoise.id).deliver      redirect_to invoices_path, notice: 'Invoice Sent successfully.'     end  

logic in mailer:

def invoice(invoice)    invoice = Invoice.find(invoice)    attachments["invoice.pdf"] = WickedPdf.new.pdf_from_string(      render_to_string(:pdf => "invoice",:template => 'invoices/#{invoice.id}/show_pdf_invoice.pdf.erb')    )      mail(to: "abc@gmail.com", subject: 'Your todo PDF is attached')  end  

method in controller

  def show_pdf_invoice      respond_to do |format|        format.html { render :layout => false }        format.pdf do      render pdf: "show_pdf_invoice"      #render :pdf => "pdf"#, :layout => 'pdf.html.erb'        end      end    end  

and in invoices/show_pdf_invoice.pdf.erb

  <h1>this is pdf invoice.<h1>  

and in company_mailer/invoice.html.erb

  please find attached pdf.  

Ruby Gem InstallGenerator Could not find generator '<name>:install

Posted: 16 Dec 2016 06:13 AM PST

I have just tried to make a ruby gem for my css grid system. However I am at the point where when rails g --help it show me:

Running via Spring preloader in process 62748  Usage: rails generate GENERATOR [args] [options]    General options:    -h, [--help]     # Print generator's options and usage    -p, [--pretend]  # Run but do not make any changes    -f, [--force]    # Overwrite files that already exist    -s, [--skip]     # Skip files that already exist    -q, [--quiet]    # Suppress status output    Please choose a generator below.    Expected boolean default value for '--markerb'; got :erb (string)  Expected string default value for '--helper'; got true (boolean)  Expected string default value for '--assets'; got true (boolean)  Rails:    assets    channel    controller    generator    helper    integration_test    job    mailer    migration    model    resource    responders_controller    scaffold    scaffold_controller    task    ActiveRecord:    active_record:devise    Devise:    devise    devise:controllers    devise:install    devise:views    Js:    js:assets    Mongoid:    mongoid:devise    Responders:    responders:install    TestUnit:    test_unit:generator    test_unit:plugin    TkdGrid:    tkd_grid:install  

When I try and run rails g tkd_grid:install I get this message:

Running via Spring preloader in process 62839  Expected boolean default value for '--markerb'; got :erb (string)  Expected string default value for '--helper'; got true (boolean)  Expected string default value for '--assets'; got true (boolean)  Could not find generator 'tkd_grid:install'. Maybe you meant 'tkd_grid:install', 'devise:install' or 'responders:install'  Run `rails generate --help` for more options.  

I am trying to inject a require in the application scss or application css file of the rails project. It shows up as a rails generator but doesnt work when I try and install.

Does anyone know how to fix this problem?

Rails with Redis and Devise not working

Posted: 16 Dec 2016 06:58 AM PST

I've added redis-rb to my rails 5 application in order to take care of backend processes managed by sidekiq.

User auth in my app is managed by Devise.

After getting all my workers etc. to function correctly, it seems that my session store is now broken. The problem is that when I sign out, the user session is not destroyed any longer, thus making it impossible to sign out.

Here is my session_store.rb config:

if Rails.env.production?    Rails.application.config.session_store :cookie_store, key: '_myapp_session', domain: ENV['SESSION_STORE_DOMAIN'], tld_length: ENV['TLD_LENGTH'].to_i  else    Rails.application.config.session_store :cookie_store, key: '_myapp_session', domain: :all, tld_length: 2  end  

I also tried to experiment with the redis-session-store gem after encountering this error but this leads to a InvalidAuthenticityToken error.

I don't really want to change my session store to use redis though. Is there any way to solve this or am I missing something?

UPDATE 1

sessions_controller.rb (devise)

def destroy      signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))      set_flash_message! :notice, :signed_out if signed_out      yield if block_given?      respond_to_on_destroy  end  

Rails, "<h2>Incomplete response received from application</h2>" in Post Json request when body is very big

Posted: 16 Dec 2016 06:15 AM PST

I am getting this error:

<h2>Incomplete response received from application</h2>  

When I am making a POST request to my app when the body is very big >1245 characters

For example if I do this request

curl -X POST \  -d '{"xxxxxxxxxxxxxxxxxxxxxxxx":{"xxxxxxxxxxxx":xxxx,"xxxxxxxxxxxx":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]},"xxxxxxxxxxxxxxxxxx":["xxxxx xxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxx","xxxxx xxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxx","xxxxx xxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxx","xxxxx xxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxx","xxxxx xx","xxxxx xxxxxxxxx","xxxxx xxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxx","xxxxx xxxxxxxxxxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxxxx xx","xxxxxx xxxxxxxx","xxxxxx xx","xxxxxx xx xxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxxxxxx xx xxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxx","xxxxxx xxxxxx xx","xxxxxx xxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xx"]}' \  http://miapplication/action.csv  

It works well.. but if I add one character more to the body:

curl -X POST \  -d '{"xxxxxxxxxxxxxxxxxxxxxxxx":{"xxxxxxxxxxxx":xxxx,"xxxxxxxxxxxx":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]},"xxxxxxxxxxxxxxxxxx":["xxxxx xxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxx","xxxxx xxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxx","xxxxx xxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxx","xxxxx xxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxx","xxxxx xx","xxxxx xxxxxxxxx","xxxxx xxxxxxxx","xxxxx xxxxxxxxx","xxxxx xxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxxxxxxxxx","xxxxx xxxxxxxxxxx","xxxxx xxxxxxxxxx","xxxxx xxxxxxxxxxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxxxx xx","xxxxxx xxxxxxxx","xxxxxx xx","xxxxxx xx xxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxxxxxx xx xxxx","xxxxxx xxxxxxxxx xx","xxxxxx xxxxx","xxxxxx xxxxxx xx","xxxxxx xxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxx"]}' \  http://miapplication/action.csv  

It fails with the above error.

I have seen several threads in SO regarding to this error but all of them are related to the setting of the secrets.yml file. And I have this file properly set in my App. Also in my case the error was happening only when they body size is crossing specific size.

Ruby - use a Constant for 'case" statements conditions

Posted: 16 Dec 2016 06:35 AM PST

I have a Ruby case statement that looks like:

case ruby_variable  when "instagram"    # do this  when "twitter"    # do that    # and so on...  else    "theres an error"  end  

I also have a constant with all the social network names (this list willl vary in time):

NETWORKS_LIST =   [   "instagram",          "twitter",          "pinterest",          .......      ]  

I would like to change this so that the conditon values, that is to say "pinterest", "twitter" and others, populate automatically into my case statement (but keep the last line else "error").

Something like a loop:

case ruby_variable  when NETWORKS_LIST[0]    do this  when NETWORKS_LIST[1]    do that  and so on...  else    "theres an error"  end  

I'm not sure how to manage this.

Factory girl object with has many through and presence validation

Posted: 16 Dec 2016 05:46 AM PST

I have a model named Beats which consists of fields like name, status, group, owner. I am writing tests using R Spec and mocking using Factory Girl, I am facing issue running specs it gives error as ActiveRecord::RecordInvalid: Validation failed: Beat Types can't be blank, I am validating presence of all the fields of form, there is a dropdown with BeatType values, its also getting called when running specs, whats the way to include it in Factory of Beat?

class Beat < ActiveRecord::Base  has_many :beat_beat_types  has_many :beat_types, through: :beat_beat_types    validates :name,:status,:group,:owner,:beat_types presence: true, length: {maximum: 255}  end    class BeatType < ActiveRecord::Base  has_many :beat_beat_types  has_many :beats, through: :beat_beat_types  end    class BeatBeatType < ActiveRecord::Base  belongs_to :beat  belongs_to :beat_type  end      Factory_File of beat    FactoryGirl.define do  factory :beat do    name    status    group    owner  end  end  

Change model to cache average rating with redis

Posted: 16 Dec 2016 05:38 AM PST

In my rails app I have a product model where I have the following method:

def average_rating          comments.average(:rating).to_f  end  

this calculates the average rating that users give to products.

How can I make Redis cache the average rating?

many thanks in advance

Deployment fails saying there's no secret_key_base even though it's present

Posted: 16 Dec 2016 05:20 AM PST

I just deployed my rails app to Kubernetes, and this is the weirdest thing I've ever seen. My app claims to be missing a secret_key_base, but not only is the token present but the app says it's running in development! What is going on?

There's a working db connection, and running the app locally with the same configuration works, but when I run on Kubernetes, I get:

Incomplete response received from application

Checking the logs shows:

$ kubectl logs -f myapp-1565535244-g6h5t  Checking the logs, I see:  App 66 stderr: [ 2016-12-16 12:21:10.7200 143/0x00000000e735b0(Worker 1) utils.rb:87 ]: *** Exception RuntimeError in Rack application object (Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`) (process 143, thread 0x00000000e735b0(Worker 1)):  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:513:in `validate_secret_key_config!'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:246:in `env_config'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/engine.rb:693:in `build_request'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:521:in `build_request'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/engine.rb:521:in `call'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:152:in `accept_and_process_next_request'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:113:in `main_loop'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:416:in `block (3 levels) in start_threads'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'  [ 2016-12-16 12:21:10.7208 33/7fa446370700 age/Cor/Con/InternalUtils.cpp:112 ]: [Client 1-1] Sending 502 response: application did not send a complete response  App 66 stderr: [ 2016-12-16 12:31:49.1605 143/0x00000000e735b0(Worker 1) utils.rb:87 ]: *** Exception RuntimeError in Rack application object (Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`) (process 143, thread 0x00000000e735b0(Worker 1)):  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:513:in `validate_secret_key_config!'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:246:in `env_config'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/engine.rb:693:in `build_request'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/application.rb:521:in `build_request'  App 66 stderr:  from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/engine.rb:521:in `call'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:152:in `accept_and_process_next_request'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:113:in `main_loop'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:416:in `block (3 levels) in start_threads'  App 66 stderr:  from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'  [ 2016-12-16 12:31:49.1608 33/7fa445aee700 age/Cor/Con/InternalUtils.cpp:112 ]: [Client 2-1] Sending 502 response: application did not send a complete response  

So I decided to go in and see what was going on:

$ kubectl exec -it myapp-1565535244-g6h5t bundle exec rails console  Running via Spring preloader in process 794  Loading development environment (Rails 5.0.0.1)  2.3.1 :001 > Rails.application.secrets.secret_key_base   => "baf43feafae8424806935f7caa71fdaa197ab20411ed070ab4ac3571384f55aabb4d18848abb3bdbf4d9d476de8fce541ebf450ec007b8c62e15b3d34f8e2780"  2.3.1 :002 > Rails.env   => "development"  

Huh? Not only is the secret present, but the app appears to be in development mode. Whatttt?

Upon further investigation of the error I found validate_secret_key_config!'s code:

def validate_secret_key_config! #:nodoc:    if secrets.secret_key_base.blank? && config.secret_token.blank?      raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"    end  end  

So I thought I'd try Rails.application.secrets.secret_token, and I get nil, which explains the error. But there's no configuration file showing SECRET_TOKEN

What do I do to get my app to run?

Ps- if you'd like to see the code, it's here

Image loading issue on html page

Posted: 16 Dec 2016 05:56 AM PST

enter image description here

See above image, When I refresh the page, the image is not loading but If I change tab from MEN to WOMEN and WOMEN to MEN then image will be display. Even If I change anything in the CSS then also image will be display. Unable to get why image is not display directly.

Other images display correctly as required but some of the images I'm getting this type of problem.

Rails Font Awesome Icons

Posted: 16 Dec 2016 05:32 AM PST

I've read a few of the pages on using font awesome with rails and that the Gemfile should include
gem 'font-awesome-rails' then run bundle install and the application.css should include *= require font-awesome however, when I try to use the icons such as <i class="icon_home"></i> to get the home icon, it shows up as blank, the grey icon should be the home icon picture

I have also tried to edit the font-awesome.css file and change the @font face and edit the applications.rb to include the fonts folder as recommended in other pages but I get the same issue

Mailchimp readTimeout error with Rails

Posted: 16 Dec 2016 04:13 AM PST

I have a Ruby on Rails application with the gem Gibbon in order to integrate my app with Mailchimp.

The code is very straightforward:

@@gibbon = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])  @@mailchimp_list = 'ID_LIST'  @@mailchimp_partner = 'ID_LIST_1'  @@mailchimp_affiliate = 'ID_LIST_2'  @@mailchimp_temp = 'ID_LIST_3'  

Then during the user subscription:

@@gibbon.lists(@@mailchimp_list).members.create(body: {email_address: email, status: "subscribed", merge_fields: {FNAME: first_name, LNAME: full_name}})  

Yesterday the last line of code threw that error:

Gibbon::MailChimpError (Net::ReadTimeout @title=nil, @detail=nil, @body=nil, @raw_body=nil, @status_code=nil)  

The error started to appear randomly and the next day it was gone and everything worked again.

I think it's an error from the Mailchimp side, what can I do in those cases?

stop a loop if model changes

Posted: 16 Dec 2016 04:16 AM PST

I'm trying to exit from a loop if model changes.

having the status attribute:

@model.status = 'started'    (0..100).each do |i|    return if status == 'stopped'    sleep(10)      # my taks...  end  

the problem is, once is started changes in the model are not reflected within the loop, any ideas?

Duplicate active record actions for model in two databases

Posted: 16 Dec 2016 04:14 AM PST

We have many clients from all around the world, and one of their requirements is to store data in USA or Europe.

To do that - one of our Model, should duplicate info in both databases (USA/Europe), which means if Model is updated, it should also fire update for second database. If new record is created, it should be created in first database, and second. So basically it should duplicate AR actions (except select) in two databases.

I have updated database.yml to store two database configurations:

development:    adapter: mysql2    encoding: utf8mb4    host: 127.0.0.1    username: xx    password: xx    database: _    pool: 25    development_usa:    adapter: mysql2    encoding: utf8mb4    host: 127.0.0.1    username: xx    password: xx    database: _usa    pool: 25  

And after that I logically thought to override actions as save http://apidock.com/rails/ActiveResource/Base/save , but knowing there are way more of doing things than one, like .save .update_attribute and seeing their source code, they all call different methods, so it is too much work to override all of these functions.

Is there a way to clone one Model in both databases after commit?

Generic method to write into YML file in ruby

Posted: 16 Dec 2016 07:33 AM PST

I have a YML file

app_config.yml

 jde_env:   py: https://jde-py.syntacom:8201/jde/E1Menu.maf   pd: https://jde.synta.com:8301/jde/E1Menu.maf   dv: https://jde-dv.synta.com:8201/jde/E1Menu.maf  

As I use write and read into YML file methods in most of my test cases , I wrote a generic method for read and write as below

def write(filename, value, *args)    arg = args.length.to_s    data = DataMagic.load(filename)    case arg      when '1'        data[args[0]]= value      when '2'        data[args[0]][args[1]] = value      when '3'        data[args[0]][args[1]][args[2]] = value    end    file_path = YML_DIR_PATH+'/'+filename    File.open(file_path, 'w') { |file| file.write data.to_yaml }  end  

For example: write('app_config.yml', '5678234', 'jde_env', 'py') it is updating '5678234' value for py

But as the above method is restricted to only 3 keys and more of hardcoded, to be more generic I am trying this logic

def write(filename, value, *args)    data = DataMagic.load(filename)    t = args.collect! { |i| " [ ' #{i}']"}    arg = t.join('')    val = "#{data}#{arg}"    val = value    file_path = YML_DIR_PATH+'/'+filename    File.open(file_path, 'w') { |file| file.write val.to_yaml }  end  

Here output is it is writing only 'value' into YML file

So my app YML file now have only 5678234

Instead of updating the key[:py] it is overwriting only the value into YML.

Can someone please help me to update only the key?

Expected Output:

 jde_env:   py: '56789234'   pd: https://jde.synta.com:8301/jde/E1Menu.maf   dv: https://jde-dv.synta.com:8201/jde/E1Menu.maf  

two sessions creating in rails devise with apartment gem

Posted: 16 Dec 2016 03:49 AM PST

I am using Apartment gem for multi tenant and devise gem for authentication every thing looks good and working fine but sometimes problem occurs when I login then devise did not take me to backend and redirect to home page.

Then I noticed in browser cookies that two session is created in local storage just like that

1: name: _newss_demo_store_session value: blablaa domain: .www.lvh.me

2: name: _newss_demo_store_session value: blabla domain: .lvh.me

And when I removed these cookies from browser then devise login take me to backend and everything start working. I did not found any solution please help or suggest any solution or If I did anything wrong.

Thanks

How to render a layout before a template

Posted: 16 Dec 2016 03:35 AM PST

I have some subclasses of ActionMailer::Base, each of which has a different version of a layout, and they all have a common template file. The template file has a portion that should depend on which layout is used.

I wrote the dependent part of the template file using instance variables, and set those value in the layouts (each layout with different values), and hoped the setting in the layout would affect rendering of the template. However, the rendering did not work the way I intended; it turned out that Rails renders the layout after the template.

Is there a way to make rendering of the template file dependent on which layout it is used with, or let the layout be rendered before the template?

My test fails with ActionView::Template::Error: undefined method `name' for nil:NilClass error?

Posted: 16 Dec 2016 05:04 AM PST

The cause of this errors is the code inside my index page which is <%= pin.user.name %>.

But when I change it to <%= pin.user.name if pin.user %>, my tests all passed.

Same question has already been posted but no accepted solution that's why I post this.

This is the full error messages:

ERROR["test_non-signed_in_user_layout_links", SiteLayoutTest, 1.3199719070007632]   test_non-signed_in_user_layout_links#SiteLayoutTest (1.32s)  ActionView::Template::Error:         ActionView::Template::Error: undefined method `name' for nil:NilClass              app/views/pins/_pin.html.erb:2:in `_app_views_pins__pin_html_erb___3167554587389080103_47088431630420'              app/views/static_pages/home.html.erb:6:in `_app_views_static_pages_home_html_erb___4092361779176196837_47088431162360'              test/integration/site_layout_test.rb:10:in `block in <class:SiteLayoutTest>'    ERROR["test_signed_in_user_layout_links", SiteLayoutTest, 2.0834625150000647]   test_signed_in_user_layout_links#SiteLayoutTest (2.08s)  ActionView::Template::Error:         ActionView::Template::Error: undefined method `name' for nil:NilClass              app/views/pins/_pin.html.erb:2:in `_app_views_pins__pin_html_erb___3167554587389080103_47088457226940'              app/views/static_pages/home.html.erb:6:in `_app_views_static_pages_home_html_erb___4092361779176196837_47088457198480'              test/integration/site_layout_test.rb:24:in `block in <class:SiteLayoutTest>'    ERROR["test_should_get_home", StaticPagesControllerTest, 2.1026109900003576]   test_should_get_home#StaticPagesControllerTest (2.10s)  ActionView::Template::Error:         ActionView::Template::Error: undefined method `name' for nil:NilClass              app/views/pins/_pin.html.erb:2:in `_app_views_pins__pin_html_erb___3167554587389080103_47088457310920'              app/views/static_pages/home.html.erb:6:in `_app_views_static_pages_home_html_erb___4092361779176196837_47088457291840'              test/controllers/static_pages_controller_test.rb:9:in `block in <class:StaticPagesControllerTest>'  

and these are the tests that have the said errors:

site_layout_test.rb

require 'test_helper'    class SiteLayoutTest < ActionDispatch::IntegrationTest    def setup      ActionMailer::Base.deliveries.clear      @user = users(:john)    end      test "non-signed in user layout links" do      get root_path      assert_template 'static_pages/home'      assert_select "a[href=?]", root_path, count: 2      assert_select "a[href=?]", about_path      assert_select "a[href=?]", new_user_session_path, count: 2      assert_select "a[href=?]", new_user_registration_path, count: 1    end      test "signed in user layout links" do      get new_user_session_path      assert_template 'devise/sessions/new'      post user_session_path, params: { user: { email: @user.email, password: 'password' } }      assert_not flash.empty?      assert_redirected_to root_path      follow_redirect!      assert_template 'static_pages/home'      assert_select "a[href=?]", new_user_session_path, count: 0      assert_select "a[href=?]", new_user_registration_path, count: 0      assert_select "a[href=?]", edit_user_registration_path      assert_select "a[href=?]", destroy_user_session_path      assert_select "a[href=?]", new_pin_path    end  end  

static_pages_controller_test.rb

require 'test_helper'    class StaticPagesControllerTest < ActionDispatch::IntegrationTest    def setup      @user = users(:john)    end      test "should get home" do      get root_url      assert_response :success      assert_select "title", full_title    end      test "should get about" do      get about_url      assert_response :success      assert_select "title", full_title("About")    end  end  

and these are my users.yml:

john:    name: John Rockefeller    email: john@rockefeller.com    encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>    created_at: <%= Time.zone.now %>    andrew:    name: Andrew Carnegie    email: andrew@carnegie.com    encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>    created_at: <%= Time.zone.now %>  

and pins.yml

quote:    description: "Lorem quote"    created_at: <%= 10.minutes.ago %>    user: john    recipe:    description: "Lorem recipe"    created_at: <%= 3.years.ago %>    most_recent:    description: "Lorem most recent"    created_at: <%= Time.zone.now %>  

Using foreign_key in rails associations has_many

Posted: 16 Dec 2016 05:11 AM PST

Could somebody explain me is my code correct.

I'm trying to get foreign_key option in rails associations.

I have 2 models: Book and Author

Book db schema:

  • name
  • user_id

Author db schema:

  • name

My models:

class Author < ApplicationRecord    has_many :books, foreign_key: :user_id  end    class Book < ApplicationRecord    belongs_to :author, foreign_key: :user_id  end  

Here I don't understand why we should define foreign_key in both models. Is it necessarily?

Why limit method is not respected in view?

Posted: 16 Dec 2016 03:17 AM PST

My application, based on the Michael Hartl's tutorial, renders in the home page a collection of the user's microposts and of the microposts of the user's following through method feed in user.rb:

  def feed      following_ids = "SELECT followed_id FROM relationships                       WHERE  follower_id = :user_id"      Micropost.where("user_id IN (#{following_ids})                       OR user_id = :user_id", user_id: id).limit(100)    end  

I added a limit of 100 microposts.
Logging in the console, I checked that the limit was respected:

2.3.1 :003 > user.feed.count     (1.6ms)  SELECT COUNT(count_column) FROM (SELECT  1 AS count_column FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships                       WHERE  follower_id = 1)                       OR user_id = 1) LIMIT $1) subquery_for_count  [["LIMIT", 100]]   => 100   

A @feed_item variable is defined in the controller as follows:

@feed_items = current_user.feed.paginate(page: params[:page])  

then it is rendered into view.
However, when I browse the page with my browser, the limit is not respected and I get all microposts (251 instead of 100, 9 pages of 30 microposts each instead of 4). Why is that?

Use controller donwolad a XLS file, and in the xls file contains the macros

Posted: 16 Dec 2016 06:34 AM PST

I need a page for donwload the file for export the data in a xls/xlsm file, and in the file xls/xlsm, i need add the code macros. with ruby on rials, how i can do this?

VBA code include in the xlsm:

Option Explicit  Option Base 1    Sub HelloWorld()    MsgBox "Hello world !"    End Sub  

Routes not changing upon editing controller

Posted: 16 Dec 2016 04:04 AM PST

I'm configuring devise to work with two omniauth providers: twitter and github. Having implimented github first, I created a github method in my OmniauthCallbacksController. Deciding later that I wanted to use twitter as well, I reconfigured my controller, discarding the github method in favor of a more sophisticated implementation for both providers.

The Problem is that when I run rake routes, the old github method is all that appears and it seems that my changes to the controllers haven't even been recognized. I can even delete everything out of the controller and my rake routes result is left unchanged. I've attached the relevant files below. Many thanks in advance for any insight you can give me.

My routes file is below (note the existence of the now nonexistent users/omniauth_callbacks#github method):

Rails.application.routes.draw do      resources :issues    resources :submissions    resources :home      devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }    match '/users/:id/finish_signup' => 'users#finish_signup', via: [:get, :patch], :as => :finish_signup      root to: "home#index"  end  

When I run rake:routes, I get the following:

$ rake routes                          Prefix Verb      URI Pattern                           Controller#Action                          issues GET       /issues(.:format)                     issues#index                                 POST      /issues(.:format)                     issues#create                       new_issue GET       /issues/new(.:format)                 issues#new                      edit_issue GET       /issues/:id/edit(.:format)            issues#edit                           issue GET       /issues/:id(.:format)                 issues#show                                 PATCH     /issues/:id(.:format)                 issues#update                                 PUT       /issues/:id(.:format)                 issues#update                                 DELETE    /issues/:id(.:format)                 issues#destroy                     submissions GET       /submissions(.:format)                submissions#index                                 POST      /submissions(.:format)                submissions#create                  new_submission GET       /submissions/new(.:format)            submissions#new                 edit_submission GET       /submissions/:id/edit(.:format)       submissions#edit                      submission GET       /submissions/:id(.:format)            submissions#show                                 PATCH     /submissions/:id(.:format)            submissions#update                                 PUT       /submissions/:id(.:format)            submissions#update                                 DELETE    /submissions/:id(.:format)            submissions#destroy                      home_index GET       /home(.:format)                       home#index                                 POST      /home(.:format)                       home#create                        new_home GET       /home/new(.:format)                   home#new                       edit_home GET       /home/:id/edit(.:format)              home#edit                            home GET       /home/:id(.:format)                   home#show                                 PATCH     /home/:id(.:format)                   home#update                                 PUT       /home/:id(.:format)                   home#update                                 DELETE    /home/:id(.:format)                   home#destroy  user_github_omniauth_authorize GET|POST  /users/auth/github(.:format)          users/omniauth_callbacks#passthru   user_github_omniauth_callback GET|POST  /users/auth/github/callback(.:format) users/omniauth_callbacks#github                new_user_session GET       /users/sign_in(.:format)              devise/sessions#new                    user_session POST      /users/sign_in(.:format)              devise/sessions#create            destroy_user_session DELETE    /users/sign_out(.:format)             devise/sessions#destroy                   user_password POST      /users/password(.:format)             devise/passwords#create               new_user_password GET       /users/password/new(.:format)         devise/passwords#new              edit_user_password GET       /users/password/edit(.:format)        devise/passwords#edit                                 PATCH     /users/password(.:format)             devise/passwords#update                                 PUT       /users/password(.:format)             devise/passwords#update        cancel_user_registration GET       /users/cancel(.:format)               devise/registrations#cancel               user_registration POST      /users(.:format)                      devise/registrations#create           new_user_registration GET       /users/sign_up(.:format)              devise/registrations#new          edit_user_registration GET       /users/edit(.:format)                 devise/registrations#edit                                 PATCH     /users(.:format)                      devise/registrations#update                                 PUT       /users(.:format)                      devise/registrations#update                                 DELETE    /users(.:format)                      devise/registrations#destroy                   finish_signup GET|PATCH /users/:id/finish_signup(.:format)    users#finish_signup                            root GET       /                                     home#index  

And my new Oauth callbacks controller looks like this:

class OmniauthCallbacksController < Devise::OmniauthCallbacksController    def self.provides_callback_for(provider)      class_eval %Q{        def #{provider}          @user = User.find_for_oauth(env["omniauth.auth"], current_user)            if @user.persisted?            sign_in_and_redirect @user, event: :authentication            set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?          else            session["devise.#{provider}_data"] = env["omniauth.auth"]            redirect_to new_user_registration_url          end        end      }    end      [:twitter, :github].each do |provider|      provides_callback_for provider    end      def after_sign_in_path_for(resource)      if resource.email_verified?        super resource      else        finish_signup_path(resource)      end    end  end  

How to route files in subdirectory on Rails?

Posted: 16 Dec 2016 03:19 AM PST

Right now, I have a landing page (home.html.erb) that is rendered with the "home" action in my "static_pages controller", and on this landing page, there is a nav bar with the following: "features" button when hover displays: a) web b) mobile.

How and what do I need to include in my routes.rb file and controller.rb file so that my home page renders /features/web when I click on the web button?

No comments:

Post a Comment