Monday, September 12, 2016

LDAP search filter w/ givenName & sn | Fixed issues

LDAP search filter w/ givenName & sn | Fixed issues


LDAP search filter w/ givenName & sn

Posted: 12 Sep 2016 07:41 AM PDT

I'm working with a LDAP query string that should select a user based on their cn OR mail OR (givenName & sn) partial matches...however, given the search string is "FirstName LastName", the space throws things off.

Here's what I have (unworking) currently. My idea is to gsub the string if it has a space and run that through another filter as an A or B case...

    search_filter = "(|(|(cn=*#{person}*)(mail=*#{person}*))(&(givenName=*#{person}*)(sn=*#{person}*)))"  

Is there a good way to capture all 3 cases in one search filter, or should I run the query string through an if statement when it has a space (in first/last name condition).

Using RoR.

concatenate activerecord relations using "or" condition

Posted: 12 Sep 2016 07:36 AM PDT

I have two queries

urgent = MassScanTask.joins(:mass_scan_list).where("mass_scan_lists.urgent = ? AND mass_scan_lists.enabled = ?", true, true).order("updated_at DESC")  not_urgent = MassScanTask.joins(:mass_scan_list).where("mass_scan_lists.urgent = ? AND mass_scan_lists.enabled = ? ", false, true).order("updated_at ASC")  

how can I get them all together urgent + not_urgent using single query? Or maybe there is some method to add one to another. I have already tried concat but it returns array and I need activerecord relations, I have also tried merge but it returns nothing.

Rails - options_for_select with range and minimum/maximum methods

Posted: 12 Sep 2016 07:25 AM PDT

I am building a filter form for my index page with some dropdown lists. For this purpose, I just need to get the min and max value from one of my model column. And I pass the name in my params from my view. Here is my code:

<%= form_tag twits_path, method: :get do %>  <%= select_tag :filter_by, options_for_select(["like", "retweet"]) %>  <%= select_tag :start, options_for_select(Twit.minimum(params(:filter_by))..10)%>  <%= select_tag :end, options_for_select(Twit.minimum(params(:filter_by))..10) %>  <%= submit_tag "Filter", :name => nil, class: "btn btn-primary" %>  <% end %>  

I can't succeed in getting min and max value from my model. It tells me wrong number of arguments (given 1, expected 0)

Thanks for your help.

Searchkick highlight: undefined method `with_details' for []:Array

Posted: 12 Sep 2016 07:28 AM PDT

I am trying to implement the excerpt highlighting into my app using SearchKick, but Rails keep telling me that I am getting the wrong object type.

My controller:

def search      @articles = Article.text_search(params[:q])    ...  

My view:

- articles.with_details.each do |article, details|    ...    p.mb-15.excerpt      = details[:highlight][:content]  

My model:

searchkick highlight: [:content]    def self.text_search(query)    if query.present?      search(             query,             fields:                [                 "title^10",                 "h1^5",                 "meta_description",                 "content"                ],             limit: 5,             highlight: {             fields: {content:                 {fragment_size: 100}               }             }         )    else      []    end  end  

Rails - Mailboxer add the recipient of the message though link

Posted: 12 Sep 2016 07:06 AM PDT

I would like to add a button to send a direct message to the user. So basically i would like to have the "Recipient" preselected/displayed in the New Conversation.

I have this form with a list of the users and one of the column is this link :

<%= link_to "Message This User", new_conversation_path(:user => search.pseudo), class: "btn btn-large btn-primary" %>   

when I click on it , i got the redirection to the page of the New Conversation: extract of the link : conversations/new?user=Nickname1 (that works, its the right nickname)

and in my form look like this : so yeah I got the select with all the nicknames , all the time :

      <div class="form-group">        <%= f.label :recipients %>        <%= hidden_field_tag :recipients, "#{@user.pseudo}" %>   # I tried @user.pseudo, @user , user.pseudo, @pseudo .... nothing worked always a NilClass or a method problem#            <%= f.select(:recipients, User.all.collect {|p| [ p.pseudo, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>            </div>  

Here is the controller for the conversations :

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  

Should I create a new action in my controller like New_link_conversation or a new form ? or maybe I am wrong with the paramater in the recipient form. I dont really know and I hope someone could help me on that :)

Thanks in advance !

PaperClip gem and Strong Parameters in Ruby on Rails.

Posted: 12 Sep 2016 06:54 AM PDT

I am using paperclip gem to upload images in my ruby on rails app. I have followed every step in the documentation and it seems like paperclip is not a problem its the strong params.

The error Im getting is as in the image.

I have mentioned image in my params code like this.

def room_params      params.require(:room).permit(:title, :description, :image)    end  

Please help! if any other information required please tell me!

How to implement deeplinking in rails 4 active admin

Posted: 12 Sep 2016 06:42 AM PDT

How to implement deep-linking (Using branch.io) in rails

For Android and Ios app, branch.io provide sdk to convert url but for app (Rails ) it does not.

"undefined method `slug'" when trying to save nested route entry (RSVP) using Friendly_id 5

Posted: 12 Sep 2016 06:34 AM PDT

I'm using friendly_id and whenever I open an event and try to add an RSVP it fails when I try to save, the error is: "undefined method `slug' for #". Your assistance will be greatly appreciated.

Event Model

 'class Event < ApplicationRecord   extend FriendlyId   friendly_id :eventname, use: [:slugged, :finders]     belongs_to :user      def should_generate_new_friendly_id?      eventname_changed?  end     has_attached_file :image, styles: { medium: "300x300>", thumb:   "100x100>" }, default_url: "/images/:style/placeholder.png"     validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/     validates :eventname, presence: true     has_many :rsvps, dependent: :destroy  end'  

Rsvp Model

`class Rsvp < ApplicationRecord      extend FriendlyId      friendly_id :eventname, use: [:slugged, :finders]      belongs_to :event  end'  

Events Controller

class EventsController < ApplicationController  before_filter :authenticate_user!, except: [:show]    def index      @events = current_user.events.all  end    def show      @event = Event.friendly.find(params[:id])  end    def new      @event = current_user.events.build  end    def create      @event = current_user.events.build(event_params)      @event.user = current_user      respond_to do |format|          if @event.save              format.html { redirect_to @event, notice: "Successfully created" }          else              format.html { render "new" }          end      end  end    def edit      @event = Event.friendly.find(params[:id])  end    def update      @event = Event.friendly.find(params[:id])      if @event.update(event_params)          redirect_to @event      else          render 'edit'      end  end    def destroy      @event = Event.friendly.find(params[:id])      @event.destroy        redirect_to events_path  end    private     def event_params    params.require(:event).permit(:eventname, :date, :time, :venue,   :description, :image)  end    end  

Rsvp Controller

class RsvpsController < ApplicationController    def index      event = Event.friendly.find(params[:event_id])      @rsvps = event.rsvps  end    def new      event = Event.friendly.find(params[:event_id])      @rsvp = event.rsvps.friendly.build          respond_to do |format|              format.html          end  end    def create      event = Event.friendly.find(params[:event_id])      @rsvp = event.rsvps.build(rsvp_params)      respond_to do |format|          if @rsvp.save          format.html { redirect_to "/thanks" }          format.js          else          format.html { render :new }          format.js          end      end  end    def thanks      render params[:page]  end     private      def rsvp_params      params.require(:rsvp).permit(:status, :name, :message)      end     end  

Routes

  resources :events do     resources :rsvps    end  

Screenshot of Error I get

Rails & Postgres - How do require an either field 1 and field 2 or field 2 and field 3?

Posted: 12 Sep 2016 06:28 AM PDT

I am writing an application for work that begins with user input in a form. I am having difficulty figuring out how to have the model validate either field 1 & field 2 to be valid, or field 2 & field 3. Is that beyond the scope of what a RoRs/Postgres model is supposed to do?

e.g. Either first_name & last_name are required or last_name & birth_date are required.

Displaying Average based on one database column in a ChartKicks chart

Posted: 12 Sep 2016 06:15 AM PDT

In my App I need the Current_user to be abel to see averages for various database columns based on the same :buisness_type as the Current_user belongs to.

After Successful Sign up the Current_user have to fill in it´s profile, part of it is this :buisness_type column in the `profile.rb´ model

<div class="form-group">      <%= f.label :buisness_type %>                      <%= f.select(:buisness_type, grouped_options_for_select(Profile::BUISNESS_TYPES),{ :class => 'form-control' })%>  </div>  

The :business_type displays as a number in the database as in buisness_type: "22"

At the moment I got this in the show method in the users_controller.rb

    @users_buisness_type = User.where(:buisness_type => current_user.profile.buisness_type).order('created_at DESC').paginate(page: params[:page], per_page: 30)  

The thing is that I´m not able to display this @users_buisness_typevariable in the Column Chart.

this is how the Chart is now

<div class="col-md-6 chart-box">                     <%= column_chart [            {name: "CarTrips #{current_user.profile.name}", data: current_user.transports.group(:transport_type).sum(:transport_km)},            {name: "CarTrips Everyone Average", data: Transport.group(:transport_type).average(:transport_km)}], { stacked: true, height: "300px", xtitle: "CarTrips", ytitle: "Km/CarTrips"} %>        </div>  

As it is now.... The chart shows the average CarTrips for every user (not only the users which have the same :business_type as the current_user)

I've tried to modify the second line in the Chart Code to {name: "CarTrips Everyone Average", data: @users_buisness_type.average(:transport_km)}

but its not working and gives me this error undefined method 'average' for nil:NilClass

Is there away to do this(show only the users which have the same :business_type as the current_user)?

I'm totally lost and it would be great if someone could help.

add image after a label in rails

Posted: 12 Sep 2016 07:17 AM PDT

I want to have an image after my label.

Below is how I am trying to do.

<%= form.label :label, :class =>'col-sm-3' do %>  <%=image_tag "qun1.png",:height=>'20px',:width=>'20px',  :style=>"margin-left: 5px;padding-left: 12px;padding-top: 7px;  top: 23px;width: 37px;" %>  <% end %>  

With this my label disappears and I can only see the image. What's wrong here?

customize time_zone_select rails 4.0

Posted: 12 Sep 2016 06:39 AM PDT

I am using time_zone_select to list all the time zones in my select box. by default it displays list as follows :

(GMT-11:00) American Samoa  (GMT-11:00) International Date Line West  (GMT-11:00) Midway Island  .  .  .  etc.  

But, I wanted it to display as follows :

American Samoa (GMT-11:00)  Alaska (GMT-09:00)   

That is I want city name first and sorted by name

I managed to sort it , but coud not change the sequence

= f.time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort_by{|e| e.name}, model: ActiveSupport::TimeZone)  

undefined method `where` for searchkick

Posted: 12 Sep 2016 07:39 AM PDT

I'm trying to add a date range filter to my searchkick

This is what i have

    @events = Event.page(params[:page]).per(10).search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)      if params[:date_from]        byebug  @events = @events.where('date BETWEEN ? AND ?', params[:date_from], params[:date_to])      end  

However the issue i'm getting is this:

*** NoMethodError Exception: undefined method `where' for #<Searchkick::Results:0x007f95eaf97f90>  

Any help would be greatly appreciated

Edit

I know this is potentially better in another question but its kinda the same question

 def search      @events = Event.page(params[:page]).per(10)      if params[:date_from]          @events = @events.where('date between ? AND ?', params[:date_from], params[:date_to])      byebug      end        @events = @events.search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)      if @events.results.any?        render 'events/results'      end  end  

Now this isn't working how i want it, I've got the event name, the datefrom and to being passed through on the params. If i type @events on the byebug it gets events in the range, but doesnt get the event i need

RoR - Removing an array element from ActionController::Parameters

Posted: 12 Sep 2016 06:05 AM PDT

In my Rails 3.2 application, I am getting the params variable in my controller as follows:

params.class         => ActionController::Parameters  params[:a].class     => ActionController::Parameters  params[:a][:b].class => Array  params[:a][:b]       => ['1', '2', '3', '4']  

When I try to delete a value in the array, it's not reflecting correctly.

e.g.

params[:a][:b].delete('1')   => "1"  

But when I again query it, there is no change in it.

params[:a][:b]   => ['1', '2', '3', '4']  

Although, if I reassign it to a variable, it's working fine.

arr = params[:a][:b]  arr.delete('1')  => "1"    arr  => ['2', '3', '4']  

Any idea why I cannot update the params object directly?

How to retrieve all users? google api

Posted: 12 Sep 2016 06:10 AM PDT

I do not understand, which headers does this API expect in order to return me a list of all users?

I've got my api_key in developers console.

GET https://www.googleapis.com/admin/directory/v1/users?key={YOUR_API_KEY}  

How do I get a list of all users?

curl -v "https://www.googleapis.com/admin/directory/v1/users/andrey.deineko@nordcloud.com?key=MY_KEY"  *   Trying 172.217.21.138...  * Connected to www.googleapis.com (172.217.21.138) port 443 (#0)  * TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256  * Server certificate: *.googleapis.com  * Server certificate: Google Internet Authority G2  * Server certificate: GeoTrust Global CA  > GET /admin/directory/v1/users/andrey.deineko@nordcloud.com?key=MY_KEY HTTP/1.1  > Host: www.googleapis.com  > User-Agent: curl/7.43.0  > Accept: */*  >  < HTTP/1.1 401 Unauthorized  < Vary: X-Origin  < WWW-Authenticate: Bearer realm="https://accounts.google.com/"  < Content-Type: application/json; charset=UTF-8  < Date: Mon, 12 Sep 2016 11:51:57 GMT  < Expires: Mon, 12 Sep 2016 11:51:57 GMT  < Cache-Control: private, max-age=0  < X-Content-Type-Options: nosniff  < X-Frame-Options: SAMEORIGIN  < X-XSS-Protection: 1; mode=block  < Server: GSE  < Alt-Svc: quic=":443"; ma=2592000; v="36,35,34,33,32"  < Accept-Ranges: none  < Vary: Origin,Accept-Encoding  < Transfer-Encoding: chunked  <  {   "error": {    "errors": [     {      "domain": "global",      "reason": "required",      "message": "Login Required",      "locationType": "header",      "location": "Authorization"     }    ],    "code": 401,    "message": "Login Required"   }  }  * Connection #0 to host www.googleapis.com left intact  

Essentially I need to retrieve all users to get a list of suspended users:

GET https://www.googleapis.com/admin/directory/v1/users?customer=my_customer  

how to sort dropdown list alphabatically in ActiveAdmin.register in rails?

Posted: 12 Sep 2016 04:37 AM PDT

I have to sort all patient list alphabetical manner from A to Z by using first name. Which will be the best way to sort for 50,000 database entries. Can anyone please suggest how to do that or is there any plugin available ?dropdownlist_image

"routes.rb:56:in `block in <top (required)>': uninitialized constant LetterOpenerWeb (NameError)"

Posted: 12 Sep 2016 05:05 AM PDT

So I tried to install some gems unsuccessfully and when I tried to run "rails server", I got a message saying I had to run "bundle install" because it couldn't find rake-10.3.2 in any of the sources (Note that before, rails server worked just fine). After all that was complete, I tried again "rails server" and I got this message:

=> Booting WEBrick  => Rails 4.1.4 application starting in development on http://0.0.0.0:3000  => Run `rails server -h` for more startup options  => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)  => Ctrl-C to shutdown server  Exiting  /home/ricardo/future/config/routes.rb:56:in `block in <top (required)>': uninitialized constant LetterOpenerWeb (NameError)      from /home/ricardo/future/vendor/bundle/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:337:in `instance_exec'      from /home/ricardo/future/vendor/bundle/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:337:in `eval_block'      from /home/ricardo/future/vendor/bundle/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:315:in `draw'      from /home/ricardo/future/config/routes.rb:1:in `<top (required)>'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `each'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `load_paths'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:16:in `reload!'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:26:in `block in updater'      from /home/ricardo/future/vendor/bundle/gems/activesupport-4.1.4/lib/active_support/file_update_checker.rb:75:in `call'      from /home/ricardo/future/vendor/bundle/gems/activesupport-4.1.4/lib/active_support/file_update_checker.rb:75:in `execute'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:27:in `updater'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application/finisher.rb:71:in `block in <module:Finisher>'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `instance_exec'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `run'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/initializable.rb:55:in `block in run_initializers'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:226:in `block in tsort_each'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:427:in `each_strongly_connected_component_from'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:347:in `block in each_strongly_connected_component'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:345:in `each'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:345:in `call'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:345:in `each_strongly_connected_component'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:224:in `tsort_each'      from /home/ricardo/.rbenv/versions/2.1.4/lib/ruby/2.1.0/tsort.rb:205:in `tsort_each'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/initializable.rb:54:in `run_initializers'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/application.rb:300:in `initialize!'      from /home/ricardo/future/config/environment.rb:5:in `<top (required)>'      from /home/ricardo/future/config.ru:3:in `block in <main>'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/builder.rb:55:in `instance_eval'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/builder.rb:55:in `initialize'      from /home/ricardo/future/config.ru:in `new'      from /home/ricardo/future/config.ru:in `<main>'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/builder.rb:49:in `eval'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/builder.rb:49:in `new_from_string'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/builder.rb:40:in `parse_file'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/server.rb:277:in `build_app_and_options_from_config'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/server.rb:199:in `app'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/server.rb:50:in `app'      from /home/ricardo/future/vendor/bundle/gems/rack-1.5.2/lib/rack/server.rb:314:in `wrapped_app'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/server.rb:130:in `log_to_stdout'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/server.rb:67:in `start'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:81:in `block in server'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:76:in `tap'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:76:in `server'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:40:in `run_command!'      from /home/ricardo/future/vendor/bundle/gems/railties-4.1.4/lib/rails/commands.rb:17:in `<top (required)>'      from bin/rails:4:in `require'      from bin/rails:4:in `<main>'  

I have no idea why rake was missing or why something is wrong with /routes.rb. Working with Ubuntu 16.04 if it's relevant.

EDIT:

Code from /routes.rb :

  55 if Rails.env.development?    56  mount LetterOpenerWeb::Engine, at: "/letter_opener"    57 end  

EDIT 2:

Gemfile:

group :development do    gem 'annotate'    gem 'letter_opener_web'    gem "better_errors"    gem "binding_of_caller"  end  

Gemfile.lock:

letter_opener (1.2.0)    launchy (~> 2.2)  letter_opener_web (1.2.3)    letter_opener (~> 1.0)    rails (>= 3.2)  

How to print group membership in groupify

Posted: 12 Sep 2016 07:24 AM PDT

I'm using Groupify gem to create separate roles in groups such as " manager" "accountint" etc. In documentation is clear how to add object to groups with certaing membership: group.add(user, as: 'manager'). But there's no explanation how to check user memberships in certain group. I want to create admin panel for changing user roles and groups so it's very important.

Edit

I solved my problem

memberships = user.group_memberships_as_member.where("group_id = ?", group.id)  memberships.each do |membership|   if membership.membership_type.present?     puts membership.membership_type   end  end  

Ruby on Rails - find Next and previous date based on param

Posted: 12 Sep 2016 05:27 AM PDT

I have added activity_logs to my application and I show @activities based on giving param_date to url.

My link/path looks like:

http://localhost:3000/users/activity_logs?param_date=2016-09-12.

I do much like to add Next day & Previous day on same page. How can I find the Next day & Previous day based on the date I have on param_date.

Ex: = link_to 'Next day', activity_logs_path(param_date: date)

So basically if param_date is 2016-09-30, Next Day would be: 2016-10-01 and Prev day: 2016-09-29

Rails 4 Error: How to get parameters from URL

Posted: 12 Sep 2016 04:31 AM PDT

I am fairly new to rails and I am struggling getting the id param out of this url:

http://localhost:3000/subscriberjobs/new?job_id=13  

Currently I am using this line of code to get it:

@job = Job.find(params[:id])  

This line directs to that:

redirect_to "/subscriberjobs/new?job_id=#{@job.id}"  

Any help on how to achieve what I am trying to do is much appreciated!

Rspec for complicated case

Posted: 12 Sep 2016 04:23 AM PDT

I'm new to RSpec, and struggling with how to test with mock. This is basically called when webhook comes in.

class InvoiceCreated    def call(event)      invoice = event.data.object        # NOTE: Skip if the invoice is closed.      if invoice.closed == false        stripe_customer = invoice.customer        payment_account = PaymentCardAccount.find_by(stripe_customer_id: stripe_customer)        card_invoice = Invoice.find_card_invoice_in_this_month_within(payment_account: payment_account)          card_invoice.process_invoice_items(stripe_customer: stripe_customer,                                           event_invoice_id: invoice.id)        card_invoice.process!(:pending, id: invoice.id)      end    end  end  

I'd love to use mock and prevent API calling for testing for two lines of code below.

 card_invoice.process_invoice_items(stripe_customer: stripe_customer,                                       event_invoice_id: invoice.id)      card_invoice.process!(:pending, id: invoice.id)  

how can I use mock for those?

Request spec error when updating

Posted: 12 Sep 2016 05:51 AM PDT

I'm trying to test my rails project with rspec and am having some difficulty, I'm trying to write a request spec that updates a product and it just doesn't seem to work:

Here is my test:

  it 'updates a product' do      put :update, id: @product, product: FactoryGirl.attributes_for(:product, title: "New Title")      @product.reload      @product.title.should eq("New Title")    end  

and here is the error I get:

   Failure/Error: put :update, id: @product, product: FactoryGirl.attributes_for(:product, title: "New Title")         URI::InvalidURIError:         bad URI(is not URI?): http://www.example.com:80update  

Any help on how to fix this would be greatly appreciated.

Verify CVC code before creating charge

Posted: 12 Sep 2016 05:50 AM PDT

I'm trying to check the user entered cvc code. I have stored stripe customer_id and the stripe card_id. I want to verify the CVC code before charging the user.

Below are code for creating charge.

charge = Stripe::Charge.create(          :amount => 1000,          :currency => "usd",          :customer => "cus_3sAc**************",          :card => "card_18m*********************",          :description => "Testing multiple card payment",          :capture => false # default true,          :cvc => 125         )  

But cvc parameter is invalid here. If I remove the cvc, it works fine. But it won't check the CVC verification. How can I check this?

Rails Affiliate system

Posted: 12 Sep 2016 03:31 AM PDT

I'm trying to build an affiliate system on my website. What I need is a simple system where people signup, enter their paypal email address and are given an affiliate link.

When someone clicks on that link and land on the website, the system recognizes the affiliate link and in case the user purchases something, the affiliate gets %50 of the sale.

Any idea how to go about that?

I spent hours researching gems for affiliates and Paypal integrations but: a) I couldn't find anything interesting b) I couldn't find a paypal integration that does this.

Thanks

How can i make conference call using twilio in rails? [on hold]

Posted: 12 Sep 2016 07:11 AM PDT

I was tried many ways to create conference call using Twilio. but I can't find clear documentation for that. can anybody help[ me?

Redirecting my Heroku app to a custom domain on BigRock

Posted: 12 Sep 2016 03:27 AM PDT

I have added my domain to heroku using heroku domains:add.

Now when I run heroku domains in my terminal, I get

=== sampleapp Domain Names  sampleapp.herokuapp.com  sampleapp.me  www.sampleapp.me  

I'm unable to configure BigRock's DNS to point to the Heroku-supplied DNS Target (which is sampleapp.herokuapp.com).

There's a domain forwarding option in BigRock, but when I use it, it shows my Heroku app in an iframe.

In the DNS management panel, I see A records, CNAME records etc., but I have no understanding of what they mean. I have, however, added a www cname with the value shown in the image below.

bigrock dns management panel

Can someone please tell me how I should go about doing this? Thank you.

Ruby on Rails:Can not call ajax callback from form_tag

Posted: 12 Sep 2016 04:05 AM PDT

In my view (/app/view/media/index.html.erb) , i have an ajax function and a form_tags: My AJAX function:

<script type="text/javascript" charset="utf-8">    $(document).ready(        function () {          $("#my_ajax").bind("ajax:success",              function (evt, data, status, xhr) {                console.log(data);                }              ).bind("ajax:error", function (evt, data, status, xhr) {            console.log("doh!")          });        });  </script>
. And my form_tags:
<%= form_tag '/delete_media', method: :delete do %> <%= submit_tag 'Delete', class: 'btn btn-danger', disabled:@media_contents.empty? , :remote => true, :id => "my_ajax" %>

Our goal : when i get response from server after submit, my_ajax function will be run.
How to do it ??? I can not trigger "my_ajax" function ? I always get JSON response from server

EDIT:

My controller :

def delete_media @medias=Media.where(id: params[:media_contents]).destroy_all render json: @medias end

Rails accepts nested attributes for multiple forms

Posted: 12 Sep 2016 03:23 AM PDT

I have two models, parent and child. I want, while i am creating parent using form, to create children for him. I have following:

parent.rb

class Parent < ActiveRecord::Base    has_many :children      accepts_nested_attributes_for :children  end  

child.rb

class Child < ActiveRecord::Base    belongs_to :parent  end  

_form.rb

<%= form_for Parent.new do |f| %>    <%= f.label :first_name %>    <%= f.text_field :first_name %></br>    <%= f.label :last_name %>    <%= f.text_field :last_name %></br>    <%= f.label :email %>    <%= f.text_field :email %></br>    <%= f.label :phone %>    <%= f.text_field :phone %></br>      <%= f.fields_for Child.new do |builder| %>        <%= builder.label :first_name %><br>        <%= builder.text_field :first_name %><br>    <% end %>      <%= f.fields_for Child.new do |builder| %>        <%= builder.label :first_name %><br>        <%= builder.text_field :first_name %><br>    <% end %>      <%= f.submit %>      <% end %>  

I want to be able, while i am creating parent, to create one or multiple children for him. If i submit this form, i get message Unpermitted parameter: child.

Also in my params hash, when i submit this form, i get only info for child in last child form. How to fix this?

This is my params permit method :

params.require(:parent).permit(:first_name, :last_name, :email, :phone, child:{})  

Deleting a job still shows the job in queue in sidekiq

Posted: 12 Sep 2016 03:43 AM PDT

job_id = BulkUploadWorker.perform_async(params)      session[:job_id] =  job_id  

This is how i am saving the job_id in session. When I removed the job from the queue

queue = Sidekiq::Queue.new      queue.each do |job|        if job.jid ==  session[:job_id]           job_removed=job.delete          end      end  

Up to here there is no problem. Now when i check its status

ap Sidekiq::Status::status(session[:job_id])  

I get :queued

To get it working again, I have to run this command in rails console

Sidekiq.redis { |conn| conn.flushdb }

Any idea why this is happening?

Edit 1

I am using a gem called sidekiq-status to get the status of the process. In my rails c when i ran sidekiq::Queue.new.find_job('jid') I got nil after deleting it. I guess the issue is with sidekiq-status gem?

Rails Get Request Send Array of Objects

Posted: 12 Sep 2016 02:04 AM PDT

Through URL I am sending an array of objects. Example

[{id: "1234", name: "DraftHouse"}]  

Im passing the request as follows using Jquery

  var tags = JSON.parse($("#admin-tags-array").val());    //Where tags is for example- [{id: "1234", name: "DraftHouse"}]    var params = $.param({tags: tags});    var url = [location.protocol, '//', location.host, location.pathname].join('');    var set_path = url + "?" + params;    window.location.href= set_path;  

On receiving the request in Rails the params[:tags] comes up like this

{"0"=>{"id"=>"1234",    "name"=>"Drafthouse"}}  

Is there a way to make rails interpert it as

[{"id"=>"1234",    "name"=>"Drafthouse"},   {"id"=>"4567",   "name"=>"New House" }]  

I need to do it in a GET request. I know it can be done in post request.

1 comment:

  1. It is nice blog Thank you provide important information and i am searching for same information to save my time Ruby on Rails Course Bangalore

    ReplyDelete