Friday, June 17, 2016

How to tell Devise to render it's views in another layout? | Fixed issues

How to tell Devise to render it's views in another layout? | Fixed issues


How to tell Devise to render it's views in another layout?

Posted: 17 Jun 2016 07:52 AM PDT

Devise keeps on rendering it's login form in the default views/layouts/application.html.erb layout, but I want it to use the Administrate layout, how can I accomplish that?

what is the best way to loop through large data with insert query in rails

Posted: 17 Jun 2016 07:41 AM PDT

i have to insert large data in lets say 20k i doubt i have written an optimised query.

users = MergeField.get_user_field_values(notification_template.merge_field,scope_users) **#returns 20k users**      if users.present?            users.each_slice(100) do |record|              record.each do |user_record|                user = User.find_by(id: user_record.user_id)                text = notification_template.title                notification_template.description = MustacheDescription.render(notification_template,user_record)                text += " " + notification_template.description                Rails.logger.info  "Merge field message: #{notification_template.description}"                construct_user_notifications(notification_template,user_record.user_id) **#=> this calls another method below which actually create notifications for every user.**                badge = (notification_template.display_screen == "suggestion") ? user.unread_suggestion_notifications.count : user.unread_option_notifications.count                devices = user.devices.with_notification_token                if devices.present?                  devices.each do |device|                    PushNotification.notify_ios(text,device.notification_token,badge,{screen: notification_template.display_screen})                    Rails.logger.info  "Sending push to user_id #{user_record.user_id} token #{device.notification_token}"                  end                end              end            end          end    def self.construct_user_notifications(notification_template,user_id)      notification_template.user_notifications.build.tap do |user_notification|        user_notification.title = notification_template.title        user_notification.subtitle = notification_template.subtitle        user_notification.description = notification_template.description        user_notification.merge_field = notification_template.merge_field        user_notification.cta = notification_template.cta        user_notification.cta_key = notification_template.cta_key        user_notification.secondary_cta = notification_template.secondary_cta        user_notification.secondary_cta_key = notification_template.secondary_cta_key        user_notification.show_useful = notification_template.show_useful        user_notification.category = notification_template.category        user_notification.display_screen = notification_template.display_screen        user_notification.sent_at = Time.current        user_notification.user_id = user_id        user_notification.filter_preferences = notification_template.filter_preferences        user_notification.save      end    end  

I have tested this for 100 users and it takes 30-40 secs. god knows how much it would take for 20k users in prod.

Rails routing wrong subdomain

Posted: 17 Jun 2016 07:40 AM PDT

I have a rails application with serveral subdomains which were administrated from the rails application.

How can I set a rout to a specific website if a subdomain is not provided?

routes looking like this at the moment

APP::Application.routes.draw do    resources :api_users, :as => :users    resources :api_courses, :as => :courses    resources :api_uploads, :as => :uploads    get "/super_admin(/:action(/:id))", :controller => :super_admin, :constraints => {:subdomain => "admin"}    get "/", :to => redirect("/super_admin"), :constraints => {:subdomain => "admin"}    get "/super_admin(/:action(/:id))", :controller => :super_admin, :constraints => {:subdomain => "admin.staging"}    get "/", :to => redirect("/super_admin"), :constraints => {:subdomain => "admin.staging"}    get "/super_admin(/:action(/:id))", :to => redirect("/")    get '/' => 'pages#home'    get '/:controller(/:action(/:id))'    post '/:controller(/:action(/:id))'    end  

CarrierWave remote_image_url not saving

Posted: 17 Jun 2016 07:34 AM PDT

I have a Rails 4 app and I'm using CarrierWave to grab an image from a url. In my form_for the url is passed into params just fine, but I can't seem to get the url to save. When I take a look at the last Stamp saved, remote_image_url is nil. I'm sure it's something simple, but the documentation is pretty woeful.

And just to confirm; CarrierWave works perfectly when uploading an image from file using the f.file_field in the form.

Here is my code:

stamp_uploader.rb:

class Stamp < ActiveRecord::Base    mount_uploader :image, StampUploader    mount_uploader :remote_image_url, StampUploader  end  

stamps_controller:

def show      @stamp = Stamp.find(params[:id])  end    def new      @stamp = Stamp.new  end    def create      @stamp = Stamp.create(stamp_params)        if @stamp.save          flash[:success] = "Thanks for your submission!"          redirect_to root_path      else          render :new      end  end    private    def stamp_params      params.require(:stamp).permit(:image, :remote_image_url)  end  

new.html.erb:

<%= form_for @stamp do |f| %>    <%= image_tag(current_user.image) %>    <%= f.label :remote_image_url, "Upload Image" %>    <%= f.text_field :remote_image_url, value: current_user.image %>      <%= f.submit %>  <% end %>  

schema.rb:

create_table "stamps", force: :cascade do |t|    t.string   "image"    t.datetime "created_at",        null: false    t.datetime "updated_at",        null: false    t.string   "remote_avatar_url"    t.string   "remote_image_url"  end  

Request returns nothing

Posted: 17 Jun 2016 07:36 AM PDT

I have managed to connect my web service to the database, but now whenever I make a request it returns nothing. The database has a couple of rows, but the web service returns zero.

get '/all_users/' do    conn = TinyTds::Client.new(username: 'nicole', password: 'pass', dataserver: 'Nikki-PC\Mydatabase', database: 'Thedatabase')    recordsArray = "{\"clientList\":["    clientArray = Array.new    sql = 'select * from dbo.ServerUsers'    records = conn.execute(sql) do |record|      client = AndroidtableClientsSearch.new(record[0], record[1], record[2], record[3], record[4])      clientArray << client.to_s    end    recordsArray << clientArray.join(',')    recordsArray << "]}"    recordsArray  end  

I'm pretty sure I am doing the execute, but this is the first time I am using tiny_tds and I am very confused. Thank you for your help.

[EDIT] This is AndroidClientsSearch:

class AndroidtableClientsSearch     def initialize(username, password, phone_number, profile_state, clasa)      @username = username      @password = password      @phone_number = phone_number      @profile_state = profile_state      @clasa = clasa  end    def to_s      { :username => "#{@username}", :password => "#{@password}", :phone_number => "#{@phone_number}", :profile_state => "#{@profile_state}", :clasa =>"#{@clasa}"}.to_json  end  end  

adding accept/deny message for gem mailboxer

Posted: 17 Jun 2016 07:19 AM PDT

I have developed a messaging system (mailboxer gem) by using (http://josephndungu.com/tutorials/private-inbox-system-in-rails-with-mailboxer). when a sender sents the message to receipient, the receipient should have two options Accept and Deny with a reply message textbox(kind of request approval) for first message then on continuos conversation(whether accepted or Denied), he should get a button of Reply.

conversation.html

    <div class="row">    <div class="spacer"></div>    <div class="col-md-6">      <%= link_to "Compose", new_conversation_path, class: "btn btn-success" %>    </div>    <div class="col-md-6 text-right">      <% if conversation.is_trashed?(current_user) %>          <%= link_to 'Untrash', untrash_conversation_path(conversation), class: 'btn btn-info', method: :post %>      <% else %>          <%= link_to 'Move to trash', trash_conversation_path(conversation), class: 'btn btn-danger', method: :post,                      data: {confirm: 'Are you sure?'} %>      <% end %>    </div>  </div>    <div class="row">    <div class="spacer"></div>    <div class="col-md-4">      <div class="panel panel-default">        <div class="panel-body">          <%= render 'mailbox/folders' %>        </div>      </div>    </div>      <div class="col-md-8">      <div class="panel panel-default">        <div class="panel-body">          <%= render partial: 'messages' %>        </div>        <div class="panel-footer">          <!-- Reply Form -->          <%= form_for :message, url: reply_conversation_path(conversation) do |f| %>              <div class="form-group">                <%= f.text_area :body, placeholder: "Reply Message", rows: 4, class: "form-control" %>              </div>              <%= f.submit "Reply", class: 'btn btn-danger pull-right' %>          <% end %>          <div class="clearfix"></div>        </div>      </div>    </div>    </div>  

conversation controller.rb

 class ConversationsController < ApplicationController    before_action :authenticate_user!      def new    end      def create      recipients = User.where(id: conversation_params[:recipients])      conversation = current_user.send_message(recipients, conversation_params[:body], conversation_params[:subject]).conversation      flash[:success] = "Your message was successfully sent!"      redirect_to conversation_path(conversation)    end      def show      @receipts = conversation.receipts_for(current_user)      # mark conversation as read      conversation.mark_as_read(current_user)    end    def reply      current_user.reply_to_conversation(conversation, message_params[:body])      flash[:notice] = "Your reply message was successfully sent!"      redirect_to conversation_path(conversation)    end    def trash      conversation.move_to_trash(current_user)      redirect_to mailbox_inbox_path    end      def untrash      conversation.untrash(current_user)      redirect_to mailbox_inbox_path    end        private      def conversation_params      params.require(:conversation).permit(:subject, :body,recipients:[])    end       def message_params      params.require(:message).permit(:body, :subject)    end  end  

Run puma workers in Production, but not in Development

Posted: 17 Jun 2016 07:28 AM PDT

I'm running the following puma config

threads_count = Integer(ENV["DB_POOL"] || ENV["MAX_THREADS"] || 15)  threads threads_count, threads_count  workers 3  preload_app!    rackup      DefaultRackup  port        ENV["PORT"]     || 3000  environment ENV["RACK_ENV"] || "development"    on_worker_boot do    ActiveSupport.on_load(:active_record) do      ActiveRecord::Base.establish_connection    end  end    before_fork do    ActiveRecord::Base.connection_pool.disconnect!  end  

It's great for production, but I don't want to spin up 3 workers or use webrick in development. I tried wrapping the worker specific code in an environment check, but that breaks the puma DSL. Any ideas for running puma in non-clustered mode in development?

Elasicsearch getting top 5 results from an aggregation with a script

Posted: 17 Jun 2016 06:54 AM PDT

I am trying to get the top 5 products sold, ordered by revenue using elasticsearch in Rails.

Here is my query:

  query = {       bool: {         filter: {          bool: {            must: [              { term: { store_id: store.id } } # Limiting the products by store           ]          }        }      }    }       aggs = {       by_revenue: {        terms: {          size: 5,          order: {revenue: "desc"}        },          aggs: {          revenue: {            max: {              script:  "doc['price_as_float'].value * doc['quantity'].value"            }             }           }         }       }         response = OrderItem.search(query: query, aggs: aggs, size: 0)  

I get the error could not find the appropriate value context to perform aggregation [by_revenue]

Thanks!

Rails Gem vendor assets Sprockets::FileNotFound

Posted: 17 Jun 2016 06:47 AM PDT

I am creating a gem for a front-end library called awesome bootstrap checkbox.

Whenever I try and use my gem, I keep being unable to access the stylesheet required in vendor (i.e. *= require awesome-bootstrap-checkbox), unless I am in the test/dummy app.

enter image description here

I've faced a similar issue before while building another gem, but this was resolved last by adding the vendor folder to the gem specification files.

  # Trying different solutions    # s.files = `git ls-files -z`.split("\x0").reject { |f| f.match(/test/) }    s.files = Dir['{lib,vendor}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md']  

However, this doesn't seem to fix the problem.

You can find my gem source code at https://github.com/frank184/awesome-bootstrap-checkbox-rails.

Before asking, I've restarted my server a dozen times, this is unrelated.

Accessing the model's attribute translations when displaying error

Posted: 17 Jun 2016 07:10 AM PDT

I've successfully created my he.yml to localize my model's attributes names, example:

      attributes:         vendor:          name: שם ספק          counter_number: מספר חשבונית          phone: טלפון          address: כתובת  

Now, displaying labels in forms using simple_form's f.input, displays it correctly, the translated value of each attribute.

the problem is, displaying errors after validation, using

<% @vendor.errors.each do |attribute, error| %>  

|attribute| for error "counter_number" for example, is displayed: "counter_number". not the translated one at the locale file [which as i mentioned previously, configured and loaded successfully]. I appended errors in a ul.errors, as shown in this screenshot: enter image description here

Thanks in advance.

Rails validation- confirmation not correct

Posted: 17 Jun 2016 06:36 AM PDT

I am trying confirmation validation in Rails4 but it does not work correctly. When i submit the form the message is "Email confirmation can't be blank" instead of "Email doesn't match confirmation" Here is my code:

enter code here  #model user.rb  class User < ActiveRecord::Base  validates :email, confirmation: true  validates :email_confirmation, presence: true  end    #view       <div class="field">  <%= f.label :email_confirmation %><br>  <%= f.text_field :email_confirmation %>  </div>  #controller  def create  @user = User.new(user_params)  respond_to do |format|  if @user.save  format.html { redirect_to @user, notice: 'User was successfully    created.' }  format.json { render :show, status: :created, location: @user }  else  format.html { render :new }  format.json { render json: @user.errors, status: :unprocessable_entity }  end  end  end  

rails - devise keeps returning html responses to ajax requests

Posted: 17 Jun 2016 07:31 AM PDT

I've been trying to get devise to return json to ajax requests, but it keeps sending back html instead. I followed this (and other, I literally looked at every link on 2 google search pages) tutorial(s) but it still sends html. Here's what I changed and where:

config/initializers/devise.rb:

added: config.http_authenticatable_on_xhr = false

created app/controllers/sessions_controller:

class SessionsController < Devise::SessionsController    respond_to :json  end  

created app.controllers/registrations_controller:

class RegistrationsController < Devise::RegistrationsController      respond_to :json  end  

added under config/routes.rb

devise_for :users, :controllers => {    sessions: 'sessions',     registrations: 'registrations'  }  

and I think that's it. but I keep getting html back. Should I delete the partial views associated with devise?

Here's what a request looks like:

Started POST "/users/sign_in" for ::1 at 2016-06-17 09:01:19 -0400 Processing by SessionsController#create as / Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}, "authenticity_token"=>"HDlnoiGZXXoarFjdlfxZL6AF0EY8Xf1K5mRwceVmVw647lG+NPJxDYstXLhiH4BGGwmNrrX8U5gZD8B3IfhS+w=="}

Use active record in ruby gem

Posted: 17 Jun 2016 05:56 AM PDT

I'm working on a ruby gem which can generate some code in other language. The gem needs to load the models in the current rails app. And it's implemented as a generator which accepts one parameter -- the table name. Inside it, read the columns definition from that table in this way:

tableklass = table_name.to_s.constantize  # get the class name from table_name  cols = tableklazz.columns  # get columns definitions.  

When I run the generator 'rails g mygen Product'. It always gave me the error below:

.../ruby/gems/2.3.0/gems/activesupport-4.2.4/lib/active_support/inflector/methods.rb:261:in `const_get': wrong constant name products (NameError)

How can I fix this error? Or whether is there other better way to do so (read table information to generate some code)?

undefined method `map' for nil:NilClass Did you mean? tap

Posted: 17 Jun 2016 07:21 AM PDT

New to rails, and walking through part 3 of a four part tutorial (https://www.youtube.com/watch?v=zeCp6IzOrpk). Have worked through a lot of errors, but this error has me stuck for the past day. Hoping someone can help.

I added the paperclip gem to my app and this error happens when I attempt to create a new book with an image file.

The Error is

NoMethodError in Books#Create

Showing /BookReview/app/views/books/_form.html.erb where line #2 raised:

undefined method `map' for nil:NilClass Did you mean? tap Trace of template inclusion: app/views/books/new.html.erb

The Application Trace is

app/views/books/_form.html.erb:2:in block in _app_views_books__form_html_erb__680817446_105363440' app/views/books/_form.html.erb:1:in_app_views_books__form_html_erb__680817446_105363440' app/views/books/new.html.erb:4:in _app_views_books_new_html_erb__1556443805_105196100' app/controllers/books_controller.rb:32:increate'

I think the problem is in my create action, within my books controller

def create        @book = current_user.books.build(book_params)      @book.category_id = params[:category_id]                if @book.save          redirect_to root_path      else          render 'new'      end  end  

When I add the following line directly under @book.category_id = params[:category_id] i can submit the form with no errors, but the file is not associated with the book when I look within the console.

@book.book_img = params[:book_img]

The last thing is the private action, which I've added the :book_img to.

def book_params   params.require(:book).permit(:title, :description, :author,:category_id, :book_img)  end  

Hoping someone can help. Thanks ahead of time!

Edit:

_form.html.erb

<%= simple_form_for @book, :html => { :multipart => true } do |f| %>     <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a category") %>     <%= f.file_field :book_img %>     <%= f.input :title, label: "Book Title" %>    <%= f.input :description %>     <%= f.input :author %>     <%= f.button :submit %>   <% end %>  

Completed 401 unauthorized calling Rails API in GET Request from IONIC

Posted: 17 Jun 2016 05:37 AM PDT

This question may sound duplicate, but I have tried all steps in the other simlar questions here but none worked. I am trying to connect to a Rails API using ionic.

My setup is Rails 4, Devise for authentication , simple_token_authentication gem for token based API requests and ionic for mobile app.

I'm able to login from ionic by passing a login request with a correct username and password to the devise session controller api and get a token after successful login through the devise api.

After that , when I try to access any controller's index with a get query using the access token http://localhost:3002/api/categories?token=1098ccee839952491a4 or http://localhost:3002/api/employers?token=1098ccee839952491a4

The response is a sign_in page of devise. In the rails log, it shows

Started GET "/api/categories?token=1098ccee839952491a43" for ::1 at 2016-06-17 17:45:55 +0530  Processing by Api::CategoriesController#index as HTML    Parameters: {"token"=>"1098ccee839952491a43"}    User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`authentication_token` = '1098ccee839952491a43'  Completed 401 Unauthorized in 3ms (ActiveRecord: 0.7ms)      Started GET "/users/sign_in" for ::1 at 2016-06-17 17:45:55 +0530  Processing by Devise::SessionsController#new as HTML    Rendered devise/shared/_links.html.erb (6.5ms)    Rendered devise/sessions/new.html.erb within layouts/login (78.3ms)  Completed 200 OK in 3850ms (Views: 3847.1ms | ActiveRecord: 0.0ms)  

I know for sure the token is correct as I have cross checked the token in the database. Also, I have included rack-cors gem and its configured for allowing any origin for cross domain request.

In my application.rb the cors entry looks like this

class Application < Rails::Application      config.active_record.raise_in_transactional_callbacks = true        config.middleware.insert_before 0, "Rack::Cors" do        allow do          origins '*'          resource '*', :headers => :any, :methods => [:get, :post, :options]        end      end      end  

The GET request in controllers.js in ionic looks like this :-

 $http({          method: 'GET',          headers:            {              'X-XSRF-TOKEN': window.localStorage.getItem("token") ,           },          url: config.apiUrl+"/categories?token="+window.localStorage.getItem("token") ,              }).then(function successCallback(response) {                                  console.log(response);                  }, function errorCallback(response) {                  $ionicPopup.alert({                      title: 'Alert',                      template: response.data.message,                  });                });     

After request is initiated, Chrome developer console shows the following message

XMLHttpRequest cannot load http://localhost:3002/api/categories?token=1098ccee839952491a43. The request was redirected to 'http://localhost:3002/users/sign_in', which is disallowed for cross-origin requests that require preflight.

The response headers I get from the server is

General

Request URL:http://localhost:3002/api/categories?token=1098ccee839952491a43  Request Method:GET  Status Code:302 Found  Remote Address:[::1]:3002  

Response Headers

view source  Access-Control-Allow-Credentials:true  Access-Control-Allow-Methods:GET, POST, OPTIONS  Access-Control-Allow-Origin:http://localhost:8100  Access-Control-Expose-Headers:  Access-Control-Max-Age:1728000  Cache-Control:no-cache  Connection:Keep-Alive  Content-Length:101  Content-Type:text/html; charset=utf-8  Date:Fri, 17 Jun 2016 12:26:13 GMT  Location:http://localhost:3002/users/sign_in  Server:WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)  Set-Cookie:_backend_session=c05LRTgzdXNVdGNFeHcwaDNtRDkxZ1RBbXFNaDFNbE1zMTV6OGhFZG1VODdON2k4ODN0ZTg3YXo5OU5hOTZkcUNmR3VTaGVRQzBOUElCNnMrODhnemVCbUhQbUs2azNHdmVnbFpoL2JiRDA5S1I4NCtsVWNhOEpqeDdoYWxXR3hHNDg5RzNRcUlpcDZ4QWswY2NmUlpYbUkvTnpaVEViNXh6ZExCZkNyTXA0allMcW1RVGg1MjRLVnpEbzlSSVk4dGRUSTNsTUZFNEFOcVJxdm1hWXNaSFEzdnlSN01DZ2FTdEJYUTdUUGxucU44cFBMbDZ6RXlhVUx2ZHArWlNCVWgyTWs2emRrSXNGbTQ3ZVVQL0NCR0E9PS0tbmFzajFXZnZnd25oUkRFRjhxSy81QT09--281b2bd6413653ca006abc80f13329d6bf3ad0f5; path=/; HttpOnly  Vary:Origin  X-Content-Type-Options:nosniff  X-Frame-Options:SAMEORIGIN  X-Request-Id:3097ec28-6d55-4c70-90c9-de221b4321e3  X-Runtime:0.021444  X-Xss-Protection:1; mode=block  

Request Headers

view source  Accept:application/json, text/plain, */*  Accept-Encoding:gzip, deflate, sdch  Accept-Language:en-US,en;q=0.8  Connection:keep-alive  Host:localhost:3002  Origin:http://localhost:8100  Referer:http://localhost:8100/  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36  X-XSRF-TOKEN:1098ccee839952491a43  

Use activerecord to find records that are not in many-to-many relation for specific user (ruby-on-rails)

Posted: 17 Jun 2016 05:45 AM PDT

Ok, my database contains three tables: users, words, statuses (it is a relation table and has no ID). Each user CAN have many words and each word CAN be repeated for different users (some users and words can be not associated). Each pair user-word has status (true or false) which is recorded in the status table.

Database:

  users            statuses              words  | id   |      | user_id         |      | id   |     | name |      | word_id         |      | word |  |      |      | status: boolean |      |      |  

I want to create a web page that will contain all the words that are HAS NO status for the current user.

Models:

class User < ActiveRecord::Base    has_many :statuses    has_many :words, through: :statuses  end    class Status < ActiveRecord::Base    belongs_to :user    belongs_to :word    validates :word, uniqueness: {scope: :user}  end    class Word < ApplicationRecord    has_and_belongs_to_many :users  end  

I wrote a request it works fine but it is ugly and I feel that is not right

def words_without_status      sql = "SELECT words.* FROM words             LEFT  JOIN (SELECT status.* FROM status             LEFT  JOIN users ON users.id = status.user_id             WHERE (status.user_id = #{current_user.id})) AS tmp             ON words.id = tmp.word_id             WHERE tmp.word_id IS NULL             ORDER BY id"      @words = ActiveRecord::Base.connection.execute(sql)  end  

Here's the code that returns all the words with status for a current_user but I need the opposite.

@words = current_user.words  

Thank you.

How to use ruby code in coffeescript jquery when we want to select an object with dynamic id?

Posted: 17 Jun 2016 05:30 AM PDT

Well, I know that's a common question and found a lot of advice how to do it but it doesn't work for me and I can't understand what's the matter.

index.html.slim

- books.each do |book|    .row class = "review_form" id = book.id      .panel        == render 'reviews/form', review: review, book: book  

book.js.coffee

$('.row.review_form').hide()    $('#new_review_button').on "click", ->      $('.row.review_form#<%= book.id %>').show()      $('#new_review_button').hide()    $('#cancel_review').on "click", ->      $(".row.review_form#<%= book.id %>").hide()      $('#new_review_button').show()  

According to instructions if you want to use ruby code in javascript you should use <%= ruby code %> as i'm doing here $('.row.review_form#<%= book.id %>').show() but nothing happens. It seems like when i write <%= in brackets it changes into one string and js doesn't understand it's a selector with ruby code. What am I doing wrong? Please, help, I'm totally confused! ><

How to include a link_to block within a label_tag

Posted: 17 Jun 2016 04:48 AM PDT

I am trying to use label_tag "Categories" and to include a plus button next to the label, which is a link_to do block that has a span (the plus button).

How to save the return customer data with stripe

Posted: 17 Jun 2016 04:25 AM PDT

I am using payola which is a rails engine for stripe payment. am using the subscriptions method to make subscription. currently users are able to make subscription and can save the data on stripe. how do i save the return data to my database. on my subscription controller i have it set like this

 def create     # do any required setup here, including finding or creating the owner object     owner = current_user # this is just an example for Devise       # set your plan in the params hash     params[:plan] = SubscriptionPlan.find_by(id: params[:plan_id])       # call Payola::CreateSubscription     subscription = Payola::CreateSubscription.call(params, owner)       # Render the status json that Payola's javascript expects     render_payola_status(subscription)     subscriptions = Subscription.new     subscriptions.stripeid = subscription.id      subscriptions.customer = subscription.customer       subscriptions.plan = subscription.plan.name        subscriptions.subscriptiondate = subscription.current_period_start         subscriptions.subscriptionenddate = subscription.current_period_end         subscriptions.save     end  

but when i check in my database its empty

const_get': uninitialized constant AdminUser (NameError)

Posted: 17 Jun 2016 04:58 AM PDT

I very new to ruby on rails , stuck with this error, below is the log file

/Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/inflector/methods.rb:261:in `const_get': uninitialized constant AdminUser (NameError)      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/inflector/methods.rb:261:in `block in constantize'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/inflector/methods.rb:259:in `each'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/inflector/methods.rb:259:in `inject'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/inflector/methods.rb:259:in `constantize'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise.rb:289:in `get'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/mapping.rb:81:in `to'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/mapping.rb:76:in `modules'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/mapping.rb:93:in `routes'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/mapping.rb:160:in `default_used_route'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/mapping.rb:70:in `initialize'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise.rb:323:in `new'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise.rb:323:in `add_mapping'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/rails/routes.rb:241:in `block in devise_for'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/rails/routes.rb:240:in `each'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/lib/devise/rails/routes.rb:240:in `devise_for'      from /Users/xyz/rails_exp/doctorcall/config/routes.rb:3:in `block in <top (required)>'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.2/lib/action_dispatch/routing/route_set.rb:432:in `instance_exec'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.2/lib/action_dispatch/routing/route_set.rb:432:in `eval_block'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.2/lib/action_dispatch/routing/route_set.rb:410:in `draw'      from /Users/xyz/rails_exp/doctorcall/config/routes.rb:1:in `<top (required)>'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:40:in `each'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:40:in `load_paths'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:16:in `reload!'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:26:in `block in updater'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.2/lib/active_support/file_update_checker.rb:75:in `execute'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:27:in `updater'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `instance_exec'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `run'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:55:in `block in run_initializers'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:54:in `run_initializers'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/railties-4.2.2/lib/rails/application.rb:352:in `initialize!'      from /Users/xyz/rails_exp/doctorcall/config/environment.rb:5:in `<top (required)>'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application.rb:92:in `preload'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application.rb:140:in `serve'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application.rb:128:in `block in run'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application.rb:122:in `loop'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application.rb:122:in `run'      from /Users/xyz/.rvm/gems/ruby-2.3.0/gems/spring-1.1.3/lib/spring/application/boot.rb:18:in `<top (required)>'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/xyz/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from -e:1:in `<main>'  

routes.rb

Rails.application.routes.draw do    devise_for :users    devise_for :admin_users, ActiveAdmin::Devise.config    ActiveAdmin.routes(self)    root             'static_pages#home'    get 'help'    => 'static_pages#help'    get 'about'   => 'static_pages#about'    get 'contact' => 'static_pages#contact'    get 'signup'  => 'users#new'    # The priority is based upon order of creation: first created -> highest priority.    # See how all your routes lay out with "rake routes".      # You can have the root of your site routed with "root"      # Example of regular route:    #   get 'products/:id' => 'catalog#view'      # Example of named route that can be invoked with purchase_url(id: product.id)    #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase      # Example resource route (maps HTTP verbs to controller actions automatically):    #   resources :products      # Example resource route with options:    #   resources :products do    #     member do    #       get 'short'    #       post 'toggle'    #     end    #    #     collection do    #       get 'sold'    #     end    #   end      # Example resource route with sub-resources:    #   resources :products do    #     resources :comments, :sales    #     resource :seller    #   end      # Example resource route with more complex sub-resources:    #   resources :products do    #     resources :comments    #     resources :sales do    #       get 'recent', on: :collection    #     end    #   end      # Example resource route with concerns:    #   concern :toggleable do    #     post 'toggle'    #   end    #   resources :posts, concerns: :toggleable    #   resources :photos, concerns: :toggleable      # Example resource route within a namespace:    #   namespace :admin do    #     # Directs /admin/products/* to Admin::ProductsController    #     # (app/controllers/admin/products_controller.rb)    #     resources :products    #   end      namespace :doctor do      post 'login', to: 'authentication#login'      post 'details', to: 'device#details'      post 'logout', to: 'authentication#logout'      post 'online', to: 'authentication#online'      post 'offline', to: 'authentication#offline'    end  end  

how to solve this

ActiveRecord::AssociationTypeMismatch:Client(#70348042846800) expected, got NilClass(#70348041556540)

Posted: 17 Jun 2016 03:35 AM PDT

I'm new to rspec and facing this issue.

ActiveRecord::AssociationTypeMismatch:Client(#70348042846800) expected, got NilClass(#70348041556540)  

Here is my controller spec,

  expect {                      post :create, {report: {name: 'name', client_ids: [1,124,87], indication_drugs: {key: {indication_id: [1]}}, criterium_ids: [1,2,3,4] }}                  }.to change(Report, :count).by(1)  

my report factory,

 FactoryGirl.define do    factory :report do      sequence(:id) { |n| n }      sequence(:business_id) { |n| "REP_#{n}" }      sequence(:name) { |n| "Report #{n}" }      is_active true      created_by 'ABC'      updated_by 'ABC'      created_at nil      updated_at nil      end    after :build do |report, cl|      report.clients << build(:clients)    end  end  

Can anyone suggest a work around for this issue.

Thanks.

Show last message in a message array

Posted: 17 Jun 2016 04:29 AM PDT

Regarding my last attempted answer, I could achieve what I wanted. Once the app is working I noticed something is different: only the person that created the message and sends a message was only showing. If I reply, I do not see the reply and I know the problem.

My Message model has tables: [:id, :user_id, :to, :body, ...]

:user_id would be similar to from as that is used to determine who created the message.

User 1 would be Client and User 2 is Student. Student sends a message to Client. Only my client side the code is as this:

#Controller Index:    @messages = Message.where(to: current_user.id) # My replies are not included here         .order(user_id: :asc, created_at: :desc)         .select('distinct on (user_id) *')  

I'm saying give me all messages that's addressed to me (:to) an id of 1.

I won't see my reply because of the :to column.

My (client) reply looks like this:

to: #student id  user_id: #client id  

And student message:

to: #client id  user_id: #student id  

So because the to now point to an id, let's say 2 I wont see the reply. I may need to change up the model but if you see an easy way, please let me know.

Edit:

Answer that works great:

@messages = Message.where(to: current_user.id).or(Message.where(user_id: current_user.id))                   .order(connection: :desc, created_at: :desc)                   .select('distinct on (connection) *')  

sqlite3 on rails: create_table using collate nocase

Posted: 17 Jun 2016 04:27 AM PDT

Using rails 4.2.0 with ruby v2.3.0p0

I want to create indexes that are case insensitive since most of my searches are case insensitive and I don't want to have to do a full table search every time.

So in my create_table migrations, I try adding lines such as:

add_index :events, :name, :COLLATE => :NOCASE  

And when I migrate I get:

== 20150515163641 CreateEvents: migrating =====================================  -- create_table(:events)     -> 0.0018s  -- add_index(:events, :submitter, {:COLLATE=>:NOCASE})  rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    Unknown key: :COLLATE. Valid keys are: :unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type  

How can I create a case-insensitive index in my migration files using SQLITE3 and rails?

Heroku unable to access certain pages, DB issue?

Posted: 17 Jun 2016 03:08 AM PDT

I have a Rails application I'm attempting to deploy to Heroku just for testing and showing by business partner. I've pushed it up got the production onto Postgres etc. It works it's up here:

However whenever I go to search I get "We're sorry, but something went wrong." This is also true when I go to view an individual. However I have no trouble logging in or going to the page where I can see everyone in the DB.

Here are the Heroku Logs:

2016-06-17T10:01:21.397942+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "search"=>"test"}  2016-06-17T10:01:21.397139+00:00 app[web.1]: Processing by ProfessorsController#search as HTML  2016-06-17T10:01:21.393865+00:00 app[web.1]: Started GET "/professors/search?utf8=%E2%9C%93&search=test" for 198.84.185.123 at 2016-06-17 10:01:21 +0000  2016-06-17T10:01:21.410950+00:00 app[web.1]: Faraday::ConnectionFailed (Connection refused - connect(2) for "localhost" port 9200):  2016-06-17T10:01:21.410952+00:00 app[web.1]:   app/controllers/professors_controller.rb:35:in `search'  2016-06-17T10:01:21.410953+00:00 app[web.1]:   2016-06-17T10:01:21.409511+00:00 app[web.1]: Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)  

`

Rails: Understanding cookies/log out users remotely

Posted: 17 Jun 2016 07:10 AM PDT

Admins should be able to log out a user remotely through the admin console.

When a user logs in, a cookie is set with cookies.signed[:user_token] The cookie is deleted with cookies.delete :user_token when user logs out.

I can only access and delete the the cookie for the current user that is sending the requests to my rails controller. The cookies hash only has the :user_token of the current user and the session_store key.

Is it possible to access the cookies of all logged in users and delete them from one account? I can't find any info on this.

An alternative way of doing this:

  1. Keep track of the log-in state(0 or 1) of every user in the database. Every time a user logs in, the state is set to 1.
  2. Allow admins to change the state to 0 through the admin console.
  3. The client browser requests the login state every minute or so. if the state is 0, send a logout request.

What do you guys think about this way of doing it?

Rails rolify gem /assosiation issue

Posted: 17 Jun 2016 04:00 AM PDT

I use rolify gem with devise for AdminUser

my Roles table

 class RolifyCreateRoles < ActiveRecord::Migration    def change      create_table(:roles) do |t|        t.string :name        t.references :resource, :polymorphic => true          t.timestamps      end        create_table(:admin_users_roles, :id => false) do |t|        t.references :admin_user        t.references :role      end        add_index(:roles, :name)      add_index(:roles, [ :name, :resource_type, :resource_id ])      add_index(:admin_users_roles, [ :admin_user_id, :role_id ])    end  end  

model 'Role'

 class Role < ActiveRecord::Base    has_and_belongs_to_many :admin_users, :join_table => :admin_users_roles      belongs_to :resource,               :polymorphic => true      validates :resource_type,              :inclusion => { :in => Rolify.resource_types },              :allow_nil => true      scopify  end  

my issue is when i want to get users witch belong to role it gives empty array instead of my adminuser object

u = AdminUser.first  u.add_role(:admin)  

u.roles => #<Role id: 1, name: "admin", admin_user_id: 1, resource_id: nil, resource_type: nil, created_at: "2016-06-16 15:03:33", updated_at: "2016-06-17 09:04:30">

and when i do

Role.first=> #<Role id: 1, name: "admin", admin_user_id: 1, resource_id: nil, resource_type: nil, created_at: "2016-06-16 15:03:33", updated_at: "2016-06-17 09:29:32">  Role.first.admin_users => []   

Has many associations error when not using default column name

Posted: 17 Jun 2016 04:22 AM PDT

I cannot make good associations when the foreign key has not the default name. I would like to access to all subjects which belongs_to one participant (foreign key = questioner_id).

It raise me an error

p = Participant.first  p.subjects    ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: subject_participants.participant_id: SELECT "participants".* FROM "participants" INNER JOIN "subject_participants" ON "participants"."id" = "subject_participants"."subject_id" WHERE "subject_participants"."participant_id" = ?  

Why does it looks for subject_participants.participant_id ? It's just a has_many association, I don't think that subject_participants table should be called in this case...

interested_id and questioner_id are from the same model but not the same role. One has to go through subject_participants table and the other has to go directly in subjects table

My models : participant.rb

class Participant < ActiveRecord::Base   has_many :subjects, foreign_key: "questioner_id", class_name: "Participant" #questioner   has_many :subjects, through: :subject_participants, foreign_key: "interested", class_name: "Participant" #interested   has_many :subject_participants   has_many :conference_participants   has_many :conferences, through: :conference_participants  end  

subject.rb

class Subject < ActiveRecord::Base   validates_presence_of  :title, :questioner, :conference, :description     has_many :subject_participants   has_many :interested, through: :subject_participants, :class_name => "Participant" #interested   belongs_to :questioner, :class_name => "Participant"    belongs_to :conference  end  

subject_participant.rb

class SubjectParticipant < ActiveRecord::Base    validates_presence_of :interested_id, :subject_id    belongs_to :interested, :class_name => "Participant"    belongs_to :subject  end  

schema.rb

create_table "participants", force: :cascade do |t|    t.string   "name"    t.datetime "created_at",                          null: false    t.datetime "updated_at",                          null: false    t.string   "email",                  default: "", null: false    t.string   "encrypted_password",     default: "", null: false    t.string   "reset_password_token"    t.datetime "reset_password_sent_at"    t.datetime "remember_created_at"    t.integer  "sign_in_count",          default: 0,  null: false    t.datetime "current_sign_in_at"    t.datetime "last_sign_in_at"    t.string   "current_sign_in_ip"    t.string   "last_sign_in_ip"  end    add_index "participants", ["email"], name: "index_participants_on_email", unique: true  add_index "participants", ["reset_password_token"], name: "index_participants_on_reset_password_token", unique: true    create_table "subject_participants", force: :cascade do |t|    t.integer  "interested_id"    t.integer  "subject_id"    t.datetime "created_at",    null: false    t.datetime "updated_at",    null: false  end    create_table "subjects", force: :cascade do |t|    t.string   "title",         null: false    t.text     "description"    t.integer  "questioner_id", null: false    t.integer  "conference_id", null: false    t.datetime "created_at",    null: false    t.datetime "updated_at",    null: false  end  

ActionView::MissingTemplate Exception: Error

Posted: 17 Jun 2016 02:41 AM PDT

class QueryFormsController < InheritedResources::Base        def create          @employee = Employee.find(params[:employee_id])          @query_form =@employee.query_form.create(query_form_params)          redirect_to employee_path(@employee)          byebug      end                private        def query_form_params        params.require(:query_form).permit(:title, :text)      end  end    show.html.erb    <%- model_class = Employee -%>  <div class="page-header">    <h3><%=t '.title', :default => model_class.model_name.human.titleize %></h3>  </div>    <dl class="dl-horizontal">    <dt><strong><%= model_class.human_attribute_name(:username) %>:</strong></dt>    <dd><%= @employee.username %></dd>    <dt><strong><%= model_class.human_attribute_name(:email) %>:</strong></dt>    <dd><%= @employee.email %></dd>    <dt><strong><%= model_class.human_attribute_name(:company_id) %>:</strong></dt>    <dd><%= @employee.company.title %></dd>    <dt><strong><%= model_class.human_attribute_name(:branch_id) %>:</strong></dt>    <dd><%= @employee.branch.title %></dd>    <dt><strong><%= model_class.human_attribute_name(:job_title_id) %>:</strong></dt>    <dd><%= @employee.job_title.title %></dd>    <dt><strong><%= model_class.human_attribute_name(:job_category_id) %>:</strong></dt>    <dd><%= @employee.job_category.title%></dd>    <dt><strong><%= model_class.human_attribute_name(:work_shift_id) %>:</strong></dt>    <dd><%= @employee.work_shift.title%></dd>    <%@employee.skills.each do |skill| %>      <dt><strong><%= model_class.human_attribute_name(:skills) %>:</strong></dt>      <dd><%= skill.title%></dd>     <% end -%>    <%@employee.educations.each do |education| %>       <dt><strong><%= model_class.human_attribute_name(:educations) %>:</strong></dt>      <dd><%= education.title%></dd>    <% end -%>     <%byebug%>    <%= render partial: '/query_form/form', :locale=>{ employee: @employee} %>    <%#= render @employee.query_form %>  </dl>  

I am getting Error

ActionView::Template::Error (Missing partial query_form/_form with {:locale=>[[:employee, #, last_sign_in_ip: #>]], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :arb, :jbuilder]}. Searched in: * "/home/rails/atul/strivepool/app/views" * "/home/rails/.rvm/gems/ruby-2.3.0/gems/twitter-bootstrap-rails-3.2.2/app/views" * "/home/rails/.rvm/gems/ruby-2.3.0/gems/devise-4.1.1/app/views" * "/home/rails/.rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-b8123d60187f/app/views" * "/home/rails/.rvm/gems/ruby-2.3.0/gems/kaminari-0.17.0/app/views" ): 26:

<%= model_class.human_attribute_name(:educations) %>:
27:
<%= education.title%>
28: <% end -%> 29: <%= render partial: '/query_form/form', :formats=>[:html], :locale=>{ employee: @employee} %> 30: <%#= render @employee.query_form %> 31: app/views/employees/show.html.erb:29:in `_app_views_employees_show_html_erb__1860382583747574564_49409220'

Resource not found: Paypal verification (email, firstname, lastname) rails

Posted: 17 Jun 2016 05:20 AM PDT

My email, firstname, lastname all work on the paypal website for verification: https://paypal-sdk-samples.herokuapp.com/adaptive_accounts/get_verified_status

Im having a problem after I submit my form I'm automatically calling the email, firstname, lastname in my controller before I set them to input boxes to make sure I have everything set up correctly. Is there something more I must do in order for this account to be verified and have status??

I get Resource not found: after submitting

Maybe the reason is because the device ip_address has to be set differently or to the current machine??? If this is the case then how do I set it to the current device??? Thank You!!!!

Error Log:

Request[post]: https://svcs.sandbox.paypal.com/AdaptiveAccounts/GetVerifiedStatus  Response[200]: OK, Duration: 1.499s    Verification Load (0.3ms)  SELECT  "verifications".* FROM "verifications" WHERE "verifications"."id" = $1 LIMIT 1  [["id", nil]]  Redirected to http://f9643d7b.ngrok.io/users/4/paypal_verification  Completed 302 Found in 1533ms (ActiveRecord: 4.5ms)      Started GET "/users/4/paypal_verification" for 221.146.103.73 at 2016-06-17 18:04:08 +0900  Cannot render console from 221.146.103.73! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

verificationController:

class VerificationsController < ApplicationController      before_action :authenticate_user!      def create      @user = User.find(params[:user_id])      @verification = current_user.verifications.create(verification_params)                      require 'paypal-sdk-adaptiveaccounts'  @api = PayPal::SDK::AdaptiveAccounts::API.new( :device_ipaddress => "127.0.0.1" )    # Build request object  @get_verified_status = @api.build_get_verified_status({    :emailAddress => "Myemail@gmail.com",    :matchCriteria => "NAME",    :firstName => "myfirstname",    :lastName => "mylastname" })    # Make API call & get response  @get_verified_status_response = @api.get_verified_status(@get_verified_status)    # Access Response  if @get_verified_status_response.success?     @get_verified_status_response.accountStatus    @get_verified_status_response.countryCode    @get_verified_status_response.userInfo  else    @get_verified_status_response.error  end          params.permit!      status = params[:accountStatus]    verification = Verification.find(params[:emailAddress])    if status == "VERIFIED"      verification.update_attributes paypal_verified: true  else       verification.update_attributes paypal_verified: false      verification.destroy  end  else      redirect_to @user.edit  end              private          def verification_params              params.require(:verification).permit(:user_id, :paypal_firstname, :paypal_lastname, :paypal_email, :paypal_verified)          end      end  

Element automatically goes down wicked_pdf Rails HTML to PDF

Posted: 17 Jun 2016 02:20 AM PDT

So as I struggled with wicked_pdf for about 1 week as it has a lot of issues, some of them I managed to fix (thanks to the solutions on internet) while other I did not. And here is one.

enter image description here This 2 elements(red and blue) are wrapped into an HTML paragraph and I force them through CSS not to break inside.

p{   -webkit-column-break-inside: avoid !important;   page-break-inside: avoid !important;   break-inside: avoid !important;  }  

This not breakable inside works for the paragraph that is highlighted with blue, and goes on the next page. but the paragraph that is red goes wildly down, leaving a massive white space(with green) between him and his parent. The thing is that no the whole block goes down but only the above element that has margins(white-space around).

And also no matter if I wrap this elements in divs or put them in a list anyway it behaves the same.

Any solutions to this or maybe someone had this issue too. Thanks you. If there you do not understand something, please ask and I will update this thread.

No comments:

Post a Comment