Monday, April 25, 2016

NoMethodError in UsersController#update | Fixed issues

NoMethodError in UsersController#update | Fixed issues


NoMethodError in UsersController#update

Posted: 25 Apr 2016 07:10 AM PDT

I have done a seperate link to change password from devise but i am getting an error of NoMethodError in UsersController#update undefined method `update' for nil:NilClass Can Someone help me please !!!

Users_controller.rb

class UsersController < ApplicationController      def show          @user = User.find(params[:id])      end        def edit        @user = User.find(params[:id])      end        def update        if @user.update(user_params)          redirect_to @user, notice: 'User was successfully updated.'        else          render :edit        end      end        private        def user_params          params.require(:user).permit(:password, :password_confirmation)        end      end  

My edit.html.erb file in users

<%= form_for(@user) do |f| %>     <div class="row">     <label class="col-xs-4" for="password">New Password</label>     <div class="col-xs-8">     <%= f.password_field :password, autocomplete: "off", :placeholder => "New Password (leave blank if you don't want to change it)", :class => 'form-control' %>     </div>   </div></br></br>   <div class="row">     <label class="col-xs-4" for="password">Confirm Password</label>     <div class="col-xs-8">     <%= f.password_field :password_confirmation, autocomplete: "off", :placeholder => "Enter password to confirm changes", :class => 'form-control' %>     </div>   </div></br></br>    <div class="field">      <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />      <%= f.password_field :current_password %>    </div></br></br>    <div class="actions">      <%= f.submit "Save", :class => "btn btn-primary" %>    </div>  <% end %>  </div></div>  

My error is

NoMethodError in UsersController#update undefined method `update' for nil:NilClass

Save my table historic with all the authorizations ids checked

Posted: 25 Apr 2016 07:01 AM PDT

I have a problem... I need save my table historic with all the authorizations ids checked, update the column authorization_origin_id and set the column refinancing_id with the refinancing id created. Example: I checked authorizations ids 2 and 3, so I create historic with two lines with authorization_origin_id 2 and 3 and the refinancing id will be 1. My code:

  def new      if params[:authorization].present?        @selected_ids = params[:authorization][:contract_number]        @authorizations = Authorization.where("contract_number in (?)", @selected_ids)        auth_params = params[:authorization]        auth_params[:contract_number].zip(auth_params[:value_solve].reject(&:blank?)).each do |contract_number, value_solve|            Authorization.where(contract_number: contract_number).update_all(value_solve: value_solve, situation: 2)        end          @authorizations.ids.each do |auth_id|          @historic_refinancing = HistoricRefinancing.create          @historic_refinancing = HistoricRefinancing.update_all(authorization_origin_id: auth_id)        end        end      @employee = Employee.search_cpf(params[:search_employee_by_cpf])      @refinancing = Refinancing.new      end  

My view:

<%= simple_form_for(@refinancing) do |f| %>    <div class="form-inputs">      <%= f.hidden_field :employee_id, value: @employee.first.id %>      <%= f.hidden_field :authorization, value: @authorization  %>      <%= f.input :contract_number %>    </div>      <h3>Reserved value</h3>    <table class="table table-condensed table-bordered table-striped">      <thead>        <th>Authorization id</th>        <th>Contract number</th>      </thead>      <% @authorizations.each do |authorization| %>        <tbody>          <tr>            <td><%= authorization.id %></td>            <td><%= authorization.contract_number %></td>          </tr>        </tbody>      <% end %>    </table>      <div class="form-actions">      <%= f.button :submit, "To Reserve" %>    </div>  <% end %>  

Actually my table historic is wrong, authorization_origin_id take, just the last (just one ever =/) value checked and refinancing_id is null

How select all unique values from select tag in my situation?

Posted: 25 Apr 2016 07:07 AM PDT

<ul class="list">        <% @freelancer.links.select {|link| ['Skype', 'ICQ', 'Jabber'].include? link.messenger_type.title }.each do |link| %>          <li class="list__item data">            <span class="data__label"><%= link.messenger_type.title %>:</span>            <span class="data__value"><%= link.url %></span>          </li>       <% end %>      </ul>  

model Link.rb

# == Schema Information  #  # Table name: links  #  #  id                :integer          not null, primary key  #  url               :string  #  freelancer_id     :integer  #  messenger_type_id :integer  #  # Indexes  #  #  index_links_on_freelancer_id      (freelancer_id)  #  index_links_on_messenger_type_id  (messenger_type_id)  #  

I have next code, wich select all links, whe messanger type include ['Skype', 'ICQ', 'Jabber']. If user double input skype, need only one first display link on page. How can i add unique links by messanger type? Thank you

shopify_app webhook creation

Posted: 25 Apr 2016 06:59 AM PDT

I am developing an app for shopify using the shopify_app gem. I list the webhooks I need in the shopify_app.rb initializer:

config.webhooks = [      {topic: 'app/uninstalled', address: "#{webhook_url}app_uninstalled", format: 'json'},      {topic: 'orders/fulfilled', address: "#{webhook_url}orders_fulfilled", format: 'json'},      {topic: 'orders/partially_fulfilled', address: "#{webhook_url}orders_partially_fulfilled", format: 'json'},      {topic: 'orders/delete', address: "#{webhook_url}orders_delete", format: 'json'},      {topic: 'orders/cancelled', address: "#{webhook_url}orders_cancelled", format: 'json'},      {topic: 'orders/paid', address: "#{webhook_url}orders_paid", format: 'json'},      {topic: 'orders/create', address: "#{webhook_url}orders_create", format: 'json'},      {topic: 'orders/updated', address: "#{webhook_url}orders_updated", format: 'json'}    ]  

However, it seems the webhooks are not created in shopify.

When I try to get the list of webhooks with @webhooks = ShopifyAPI::Webhook.find :all, I receive an empty array.

Am I doing something wrong?

When are webhooks created?

Restrict Access to a Rails WebApp

Posted: 25 Apr 2016 06:58 AM PDT

I'm currently building an app. for my office to use however we don't want anyone outside of our office's network to be able to access it. Because we are a part of a larger network I can't be sure that IP addresses won't randomly change. Is there any way to better restrict access by something that won't randomly change than by IP address? I was thinking of keeping the application running on a local server that everyone could access but then that opens the door to other issues and is no longer an option. Any tips would be greatly appreciated! Thanks.

Using delayed job I want to modify reschedule_at based on error message

Posted: 25 Apr 2016 06:45 AM PDT

Using the error, failure and reschedule_at callbacks is there a way to make reschedule_at time depend on what type of error i receive?

I have set the reschedule_at method but if affects all jobs of this type. I don't know where to handle this behavior based on error type and in what handler.

DeviseAuthToken Rails 4

Posted: 25 Apr 2016 06:50 AM PDT

I'm using DeviseTokenAuth and I can't figure out why:

warden.user(rc.to_s.underscore.to_sym)  

is returning me nil in set_user_by_token.rb (a file of the gem).

I've print rc.to_s.underscore.to_sym which is returning "user".

What's going out here? How can I debug that?

Ordering by date in Ruby on Rails

Posted: 25 Apr 2016 06:54 AM PDT

I am iterating over a set of objects in Ruby on Rails like so :

  <% @subject.Association.each do |horse| %>   <tr>    <td>      <%= horse['Name'].to_s %>      <%= horse['Size'] %>    </td>    </tr>     <% end %>  

The horse object has a date field, called dateRode.

I would like to order by this field.

I am not a ruby developer, but I tried a number of ways to do this resulting in only syntax errors e.g

<% subject.association.each do |horse|-> { order by "dateRode" DESC } %>  

How can I do this in my code without editing ActiveRecords etc?

rails5 api + devise_token_auth: no access-token and uid returns after login successfully via omniauth2

Posted: 25 Apr 2016 06:24 AM PDT

I am using devise_token_auth for omniauth2 login with weibo and qq. Yes, I am trying to use rails5 api feature!

After setup and using omniauth test_mode, I seems like login successfully but not login info(access_token, expiry, client and uid) return in the header of response.

Here is model, I apply candidate rather than user as authentication resource.

#app/models/candidate.rb    class Candidate < ApplicationRecord    devise :database_authenticatable, :trackable, :omniauthable    include DeviseTokenAuth::Concerns::User      has_many :recruitments    attr_writer :password, :password_confirmation  end  

Using dummy omniauth successful info.

#config/environment/development.rb  #OmniAuth Fake  OmniAuth.config.test_mode = true  OmniAuth.config.mock_auth[:qq_connect] = OmniAuth::AuthHash.new(    {        provider: 'qq_connect',        extra: { raw_info: { nickname: :dev } },        info: { nickname: :dev },        uid: '123456'    })  OmniAuth.config.mock_auth[:weibo] = OmniAuth::AuthHash.new(    {        provider: 'weibo',        extra: { raw_info: { nickname: :dev } },        info: { nickname: :dev },        uid: '1234567'    })  

So, when I send a get request to http://localhost:3000/auth/weibo, application redirect me to http://localhost:3000//auth/weibo/callback. It returns 200 Ok.

As far, everything seems fine. And also I check DB, which shows that candidate(authentication resource) was created, and its token changed with every request to it.

But look at the header of response, I find nothing useful(access-token, expiry etc) inside.

#Header of response    Cache-Control →max-age=0, private, must-revalidate  Connection →close  Content-Type →text/plain; charset=utf-8  ETag →W/"7215ee9c7d9dc229d2921a40e899ec5f"  Server →thin 1.6.2 codename Doc Brown  X-Content-Type-Options →nosniff  X-Frame-Options →SAMEORIGIN  X-Request-Id →d91648bb-3e69-4d23-8dfa-9eedfafeac26  X-Runtime →0.085038  X-XSS-Protection →1; mode=block  

So My question is How to get auth info(likes access-token, client etc) after login with omniauth2?

Regards!

Can I create a Rails resource route called 'index'?

Posted: 25 Apr 2016 06:16 AM PDT

I want to add a resource route called index to an application but the generated routes aren't as expected. However, if I use another name (such as show_index), they are. To demonstrate, I'll begin with a vanilla Rails app that has no routes:

$ rake routes  You don't have any routes defined!  

I add the below into config/routes.rb:

  resources :items  

Which produces the usual resourceful Rails routes:

    Prefix Verb   URI Pattern               Controller#Action  item_index GET    /item(.:format)           item#index             POST   /item(.:format)           item#create    new_item GET    /item/new(.:format)       item#new   edit_item GET    /item/:id/edit(.:format)  item#edit        item GET    /item/:id(.:format)       item#show             PATCH  /item/:id(.:format)       item#update             PUT    /item/:id(.:format)       item#update             DELETE /item/:id(.:format)       item#destroy  

I want to add a custom index route that invokes the show action with an added parameter. I change the route definition to:

  resources :item do      member do        get 'index' => 'items#show', with: 'index'      end    end  

Giving this diff of the routes:

>       item GET    /item/:id/index(.:format) items#show {:with=>"index"}  <       item GET    /item/:id(.:format)       item#show  ---  >            GET    /item/:id(.:format)       item#show  

Rather than just adding one route, it alters one and adds a second, and neither have the expected method prefixes (which should have the form <route>_<resource>, i.e. index_item). However, if I use a different name:

get 'show_index' => 'items#show', with: 'index'  

then the diff is as I would expect - one new route with the expected method prefix:

> show_index_item GET    /item/:id/show_index(.:format) items#show {:with=>"index"}  

I expect there's a problem using index because the implied resources routes use that name, although I don't think they use it in a way that would clash. It looks to me like I should to be able to add a new index route which would become index_item (in contrast to the existing item_index).

I know I can work around the problem, as I have demonstrated, by using a different name. But index reads better than show_index.

So my question asks is there a way to add a route using the word index ?

Missing some rabbitMQ messages

Posted: 25 Apr 2016 06:01 AM PDT

I have strange issue, while broadcasting messages to clients. This is my code, that is responsible for publishing messages:

AMQP.start(:host => property(:amqp_host), :vhost => property(:amqp_vhost), :user => property(:amqp_user), :pass => property(:amqp_pass)) do        exchange = MQ::Exchange.new(MQ.new, :topic, "games" )        exchange.publish( @message, :key => @key )        AMQP.stop { EM.stop }  end  

I'm using old version of AMQP gem(rails 2.3.8). The problem is - When there is only one client, this client gets all messages, if there are more than 1 client, all messages gets last connected client. I've tried to publish to different keys, and split clients through pool of available keys, but still same. Is there something i've missed?

Using mailchimp-api-gem limit and start params do not work on list method

Posted: 25 Apr 2016 06:01 AM PDT

I'm using the mailchimp-api gem to pull out a series of campaigns. All other parameters seem to work on the list method except for limit. http://www.rubydoc.info/gems/mailchimp-api/2.0.6/Mailchimp/Campaigns#list-instance_method

When i set the limit higher than 25 in [:data] i only get 25 responses yet total still says 67. I've tried it with limit set to both 67 and 99 and still only get 25 responses. The start parameter also doesn't work to attempt multiple calls in order to get all of the data.

I'm wondering if this is an api version issue and if so how do i default to api2 on mailchimp?

how to integrate arbor.js in ruby on rails

Posted: 25 Apr 2016 07:06 AM PDT

I need to add arbor.js in my ruby on rails project for graphs visualization

I change the gemfile adding the gem: gem 'arbor-rails', '~> 0.0.4', and then do a bundle install.

Also, in my vendor/assets/javascript/ add a file called arbor.js with the arbor.js data from https://github.com/samizdatco/arbor

In my app/assets/javascripts/application.js I add the line //= require arbor

With all that, it´s supposed to work fine. I use the next example for a simple graph:

https://gist.github.com/RC1140/1036344/01df1354ada1de2c0cc0b0b916cd4117ff14bf47

Someone can help me?

undefined method 'name' in nil:NilClass

Posted: 25 Apr 2016 05:56 AM PDT

So we are currently working on a website for an important customer, and we have run into a roadblock that has prevented further progression. We were working on relationships between database tables and one of the tables is not recognizing the above named method. Here is the code:

organizers_controller.rb:

  # GET /organizers.json  def index    @organizers = Organizer.all  end    # GET /organizers/1  # GET /organizers/1.json  def show  end    # GET /organizers/new  def new    @organizer = Organizer.new  end    # GET /organizers/1/edit    def edit  end    # POST /organizers  # POST /organizers.json  def create    @organizer = Organizer.new(organizer_params)    respond_to do |format|    if @organizer.save      format.html { redirect_to @organizer, notice: 'Organizer was successfully created.' }      format.json { render :show, status: :created, location: @organizer }    else      format.html { render :new }      format.json { render json: @organizer.errors, status: :unprocessable_entity }    end  end  end    # PATCH/PUT /organizers/1  # PATCH/PUT /organizers/1.json  def update    respond_to do |format|      if @organizer.update(organizer_params)        format.html { redirect_to @organizer, notice: 'Organizer was successfully updated.' }      format.json { render :show, status: :ok, location: @organizer }    else      format.html { render :edit }      format.json { render json: @organizer.errors, status: :unprocessable_entity }    end  end  end    # DELETE /organizers/1  # DELETE /organizers/1.json  def destroy    @organizer.destroy    respond_to do |format|      format.html { redirect_to organizers_url, notice: 'Organizer was successfully destroyed.' }    format.json { head :no_content }  end  end    private    # Use callbacks to share common setup or constraints between actions.    def set_organizer      @organizer = Organizer.find(params[:id])    end    # Never trust parameters from the scary internet, only allow the white list through.  def organizer_params    params.require(:organizer).permit(:name)  end  end  

show.html.erb:

<p id="notice"><%= notice %></p>    <p>    <strong>Title:</strong>    <%= @event.title %>    <strong>Organization</strong>    <%= @organizer.name %>  </p>    <%= link_to 'Edit', edit_event_path(@event) %> |  <%= link_to 'Back', events_path %>  

Relevant error:

undefined method `name' for nil:NilClass  

Excuse the spacing issues, the code didn't translate well over to the codeblock

What does `status: :ok` do in `render json:` (Rails)

Posted: 25 Apr 2016 06:01 AM PDT

What doesstatus: :ok do in render json: {round: @round}, status: :ok?

Sometimes everything works without it, but sometimes its necessary to prevent an error like,

ActionController::UnknownFormat (ActionController::UnknownFormat):  

I use Angular for front-end and Rails for back-end.

My understanding is that this final line in the Rails controller action converts the server response back to json format so Angular can read it (not 100% confident this is correct explanation).

But I don't understand why to use one or the other of the following. Sometimes one works and sometimes the other does.

  1. render json: {round: @round}, status: :ok1
  2. respond_to :json and respond_with @round

Can anyone share some insight?

Memory vs Database difference in a variable value

Posted: 25 Apr 2016 05:44 AM PDT

I have a pdf attachment boolean flag set in my application and my database shows it to be set true. But when my debugger loads and I inspect the variable it is showing false always.

This is the sql generated when I fetch the flag.

CACHE (0.0ms)  SELECT  `spree_products`.* FROM `spree_products` INNER JOIN `spree_variants` ON `spree_products`.`id` = `spree_variants`.`product_id` INNER JOIN `spree_line_items` ON `spree_variants`.`id` = `spree_line_items`.`variant_id` WHERE `spree_products`.`deleted_at` IS NULL AND `spree_variants`.`deleted_at` IS NULL AND `spree_line_items`.`order_id` = 1070722790  ORDER BY spree_line_items.created_at ASC LIMIT 1  [["order_id", 1070722790]]  

This is what I used for the above result:

products.first.attached_pdf  

This always result in false. I don't know if it is bringing the data from memory cache or what but this is being quite nuisance for me right now. Why are the memory and database values different? Any help would be great!

Rails Braintree webhook integration not working

Posted: 25 Apr 2016 05:27 AM PDT

i'm trying to implement Braintree's webhook capabilities into my rails app but with no success. I have followed every single step in their documentation - https://developers.braintreepayments.com/guides/webhooks/overview but it still doesn't work.

Here's the code in my webhook controller:

class BraintreeWebhookController < ApplicationController    skip_before_filter :verify_authenticity_token    require 'braintree'      def webhook      webhook_notification = Braintree::WebhookNotification.parse(          bt_signature_param,          bt_payload_param      )        #operations here onwards      #...        render status: 200    end      def get_webhook      challenge = bt_challenge_param      challenge_response = Braintree::WebhookNotification.verify(challenge)        render plain: challenge_response, status: 200    end      private    def bt_signature_param      return params[:bt_signature]    end      def bt_payload_param      return params[:bt_payload]    end      def bt_challenge_param      return params[:bt_challenge]    end  end  

The webhook function is for the HTTP POST request while the get_webhook function is for HTTP GET request. I'm not actually sure what the coding in the get_webhook function does and it's not in Braintree's documentation but I found it in one of a user's sample application on Github.

I have configured the routes as below:

post 'braintree/webhook' => 'braintree_webhook#webhook'  get 'braintree/webhook' => 'braintree_webhook#get_webhook'   

Once i hit the 'Check URL' button in Braintree's webhook control panel, nothing happens except for the error message

Last delivery unsuccessful. Invalid server response

Any help would be very much appreciated and by the way, my site is SSL encrypted and uses HTTPS protocol, don't know if that affects the webhook operations or not.

Using rails_admin with rails_api

Posted: 25 Apr 2016 05:13 AM PDT

I originally posted this as an issue on rails_api GitHub, but am now posting it here due to inactivity.

I'm trying to use rails_admin with a Rails 5 API application. I have this working up to the point that I can either have a functioning rails_admin panel or working API requests. The issue seems to be that rails_admin depends on ActionView::Layouts, which after included causes issues for API requests.

Gemfile:

gem 'rails', '>= 5.0.0.beta3', '< 5.1'  ...  gem 'rack-pjax', github: 'afcapel/rack-pjax'  gem 'remotipart', github: 'mshibuya/remotipart'  gem 'kaminari', github: 'amatsuda/kaminari', branch: '0-17-stable'  gem 'rails_admin', github: 'sferik/rails_admin'  

I configured my application to use ActionDispatch::Flash:

module MyApp    class Application < Rails::Application      ...      config.middleware.use ActionDispatch::Flash    end  end  

I configured extra modules for Rails API, ApplicationController:

class ApplicationController < ActionController::API    include Knock::Authenticatable    include Pundit      # RailsAdmin support    include AbstractController::Helpers    include ActionController::Flash    include ActionController::RequestForgeryProtection    include ActionController::MimeResponds    include ActionController::HttpAuthentication::Basic::ControllerMethods    include ActionView::Layouts  end  

With these changes the Rails Admin dashboard seems to run fine. However, when I'm trying to access the JSON resources in my application, the following error is thrown:

Error:  BookingsControllerTest#test_should_get_index:  ActionView::MissingTemplate: Missing template bookings/index, application/index with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :haml]}. Searched in:    * "/Users/richard/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/rails_admin-355dc80f8a20/app/views"  

This is the controller code:

class BookingsController < ApplicationController    def index      @bookings = find_bookings      render json: @bookings, include: ['customer', 'client'], meta: meta    end  end  

This only happens after I include the ActionView::Layouts module in the top level ActionController::API class to support Rails Admin.

Have been trying things for a couple of hours now.. does anyone have a suggestion?

Rails: A user can create other users with different set of permissions

Posted: 25 Apr 2016 05:46 AM PDT

This might be a duplicate of a question already asked but i haven't found the one that suits my condition yet.

I am developing a system where there's a user (not an admin) who is registering himself using devise. What i want is to allow this user to create different users and provide them different set of permissions (so can't be predefined permissions and hence, cant use cancan as far as i am aware). To clarify more, this is the table structure i have come up with yet. Please guide me if i am going on the wrong path here.

USER:

id,  name,  other-details  

PERMISSION

id,  name, (name of the section such as gallery, report or users)  create,  edit,  view,  user_id (the user whose permissions are defined here)  

Here, create, edit and view are the permissions that the user would have. If the edit is true, he'll be able to edit that particular section. I'm sorry if this is not clear. I found Johan's answer (last one) Database schema for ACL match my scenario however i am not sure if its the right way. Also, i am not sure how to implement the SET mentioned there.

Thanx in advance. Also please feel free to ask for more details if required. I'm clueless about how right this method will be.

P.S: Newbie in Rails Here.

I want a seperate link only for change password in ruby on rails !!! How Can i do?

Posted: 25 Apr 2016 05:29 AM PDT

I dont want change password option in devise (edit registrations). rather, i would like to add a link or form for changing password in separate page. can anyone help me !!!

Rails Omniauth twitter gem - not authorizing user correctly

Posted: 25 Apr 2016 04:59 AM PDT

I'm building a Rails app which allows users to create and book onto events. I've integrated the twitter omniauth gem along with devise. It logs me in correctly and redirects back however when I click on the link to create an event or book an event the app redirects me back to the sign in page. I've set the site up so that only signed in users can do this but it doesn't appear to cover the omniauth integration. I also have no way to sign-out from one user to another if I use Twitter to sign in. I want to add Facebook auth also but want to fix this first. What code (inc. validations) am I missing to cover these functions?

Here's the relevant code so far -

Events Controller -

class EventsController < ApplicationController  before_action :find_event, only: [:show, :edit, :update, :destroy,]  # the before_actions will take care of finding the correct event for us  # this ties in with the private method below  before_action :authenticate_user!, except: [:index, :show]  # this ensures only users who are signed in can alter an event    def index      if params[:category].blank?          @events = Event.all.order("created_at DESC")      else          @category_id = Category.find_by(name: params[:category]).id          @events = Event.where(category_id: @category_id).order("created_at DESC")      end      # The above code = If there's no category found then all the events are listed      # If there is then it will show the EVENTS under each category only  end    def show  end    def new      @event = current_user.events.build      # this now builds out from a user once devise gem is added      # after initially having an argument of Event.new      # this assigns events to users  end  # both update and create actions below use event_params as their argument with     an if/else statement   def create      @event = current_user.events.build(event_params)      # as above this now assigns events to users      # rather than Event.new        if @event.save          redirect_to @event, notice: "Congratulations, you have successfully created a new event."      else          render 'new'      end  end    def edit      # edit form      # @edit = Edit.find(params[:id])      @event = current_user.events.find(params[:id])  end    def update      if @event.update(event_params)          redirect_to @event, notice: "Event was successfully updated!"      else          render 'edit'      end  end    def destroy      @event.destroy      redirect_to root_path  end    private    def event_params      params.require(:event).permit(:title, :location, :date, :time, :description, :number_of_spaces, :is_free, :price, :organised_by, :url, :image, :category_id)      # category_id added at the end to ensure this is assigned to each new event created  end    def find_event      @event = Event.find(params[:id])  end                end  

Application controller -

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception       before_filter :configure_permitted_parameters, if: :devise_controller?      protected       def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_up) << :name      devise_parameter_sanitizer.for(:account_update) << :name      end      # the application controller    # handles everything across the site      # make the current_user AND the logged_in? available to    # be used in the views as well as the controllers    helper_method :current_user    helper_method :logged_in?    helper_method :logged_out?      def current_user      # this is who I am signed in as      @current_user = User.find(session[:uid])    end      def logged_in?      # am i logged in?      # do i have a cookie called uid?      session[:uid].present?    end      def make_sure_logged_in      # If I'm not logged in, redirect me to the log in page      if not logged_in?        flash[:error] = "You must be signed in to see that page"        redirect_to new_session_path      end    end      def logged_out?      session[:uid] = nil      flash[:success] = "You've logged out"      redirect_to root_path    end    end  

index.html.erb - events

<header>  <div class="category">            <%= link_to  image_tag('MamaKnows.png'), root_path, id: "home" %>          <% Category.all.each do |category| %>                  <li><%= link_to category.name, events_path(category: category.name) %></li>                      <% end %>                      <!-- The code loop above creates category links to the home page -->        </div>  <nav id="nav">        <% if logged_in? %>              <%= link_to 'Create Event', new_event_path %>              <%= link_to 'Account', user_path(current_user) %>              <%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>          <% else %>              <%= link_to "Create an Event", new_user_session_path %>          <% end %>               </nav>        </header>       <% @events.each do |event| %>      <%= link_to (image_tag event.image.url), event %>    <h2><%= link_to event.title, event %></h2>  <h2><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h2>    <% end %>  

OmniauthCallback Controller

class OmniauthCallbacksController < Devise::OmniauthCallbacksController    def twitter         @details = request.env["omniauth.auth"]        @provider = @details["provider"]      @provider_id = @details["uid"]        @user = User.where(provider: @provider, provider_id: @provider_id).first        if @user.present?          #sign them in      else          # make a new user          @user = User.new          @user.provider = @provider          @user.provider_id = @provider_id            # because of has_secure_password - will this work?          @user.password = "AAAAAA!!"          @user.password_confirmation = "AAAAAA!!"            # let's save the key and secret          @user.key = @details["credentials"]["token"]          @user.secret = @details["credentials"]["secret"]            # lets fill in their details          @user.name = @details["info"]["name"]          if @provider == "twitter"? @user.save!(:validate => false) : @user.save!          # the above if statement allows for twitter to skip validation which requires an email          @user.email = @details["info"]["email"]          end            @user.save!      end              session[:uid] = @user.id           flash[:success] = "You've signed in"          redirect_to root_path    end      def password_required?      super && provider.blank?  end              end  

Any assistance would be appreciated.

Post tweet with net/http getting error in ruby

Posted: 25 Apr 2016 06:32 AM PDT

I am getting this error when i trying to post a tweet with the help of net/http in ROR. Please check the code and help me if any mistake I did. Below are my code

require "base64"  require "json"  require "net/http"  require "net/https"  require "uri"    ### Setup access credentials    consumer_key = "consumer_key"  consumer_secret = "consumer_secret"    ### Get the Access Token    bearer_token = "#{consumer_key}:#{consumer_secret}"  bearer_token_64 = Base64.strict_encode64(bearer_token)    token_uri = URI("https://api.twitter.com/oauth2/token")  token_https = Net::HTTP.new(token_uri.host,token_uri.port)  token_https.use_ssl = true    token_request = Net::HTTP::Post.new(token_uri)  token_request["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"  token_request["Authorization"] = "Basic #{bearer_token_64}"  token_request.body = "grant_type=client_credentials"    token_response = token_https.request(token_request).body  token_json = JSON.parse(token_response)    access_token = token_json["access_token"]    ### Use the Access Token to make an API request    timeline_uri = URI("https://api.twitter.com/1.1/statuses/update.json?screen_name= testingclient1")  timeline_https = Net::HTTP.new(timeline_uri.host,timeline_uri.port)  timeline_https.use_ssl = true    timeline_request = Net::HTTP::Post.new(timeline_uri)  timeline_request["Authorization"] = "Bearer #{access_token}"  timeline_request.set_form_data("status" => "your tweet")  timeline_response = timeline_https.request(timeline_request).body    timeline_json = JSON.parse(timeline_response)  

It giving error on console

"code"= 220, "message"= "Your credentials do not allow access to this resource."  

Cancancan: set authorization for all controllers

Posted: 25 Apr 2016 04:53 AM PDT

Can I set autorization for all application without putting load_and_authorize_resource in each controller?

How to write checkbox active record search using using scope

Posted: 25 Apr 2016 07:10 AM PDT

How to do checkbox search through scope in ruby

i have form like this

<% VenueCategory.all.each do |c| %>   <%= check_box_tag("venue_categories[]", c.id)%>   <%= c.name%>  <% end %>`  

i want to search venue categories if more than one option is selected. How to do it with scope

i tried like this in my property.rb model

scope :venue_category, -> (venue_categories_id) { where venue_category_ids: venue_categories }

controller:

@properties = Property.where(:status=>'1') @properties = @properties.venue_categories(params[:venue_categories]) if params[:venue_categories].present?

i'm getting error when i tried this.

I don't know how to do multiple checkbox options search with scope. Please help me if anyone knows.

Any help is appreciable.

Payflow payment integration in ruby on rails

Posted: 25 Apr 2016 04:55 AM PDT

I'm using paypal for payment and here is main function and parameters which are used for payment.

def self.paypal_url(.....)  values = {          :business => 'email@id.com',          :cmd => '_cart',          :upload => 1,          :return => return_url,          :invoice => "#{customer.id}_#{sType.id}_#{Time.now}",          :notify_url => notify_url      }      values.merge!({                        "amount_1" => amount,                        "item_name_1" => sType.show_title,                        "discount_amount_1" => discount                        # "quantity_1" => '1'                    })      "https://www.paypal.com/cgi-bin/webscr?" + values.to_query  end  

But now i want to use PayFlow. Kindly guide me which parameter i have to change and what will be the final url as for payment is "https://www.paypal.com/cgi-bin/webscr?" + values.to_query.

An unhandled lowlevel error occurred. The application logs may have details

Posted: 25 Apr 2016 04:10 AM PDT

I deployed my first rails app to digital ocean droplet following deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma

after lot of issues, I completed all the steps almost in 4 days.

But now when I point my web browser to my server IP it say

An unhandled lowlevel error occurred. The application logs may have details.

whats the issue now?

How to access previous updated_at?

Posted: 25 Apr 2016 03:56 AM PDT

I have model in which I keep track of the field updated_at.

Is there a way I can track the previous updated_at?

For example

updated_at = A (where A is an actual datetime stamp)

Some work is done then save is called

updated_at = B (where B is an actual datetime stamp)

Is there a way I can access the previous updated_at i.e. A?

Stripe Rails: Invalid integer: 1.06

Posted: 25 Apr 2016 05:48 AM PDT

I can't get my head around this one.

My form passes a params of 106 which is £1.06.

enter image description here

Charging the card:

amount = params[:amount].to_f  begin    charge = Stripe::Charge.create(      :amount => amount / 100,      :currency => "gbp",      :source => token,      :description => "Example charge"    )  rescue Stripe::CardError => e    # The card has been declined  end  

How to prevent:

Invalid integer: 1.06

Where does the integer comes from? I have converted that to float.

How to write active record using using scope

Posted: 25 Apr 2016 03:34 AM PDT

How to write active record for price less than or equal to and price less than or equal to by scope in ruby.

i tried like this.

scope :price, -> (price_lteq_or_price_gteq) { where("price_paisas >= ? or price_paisas <= ?", price_lteq_or_price_gteq, price_lteq_or_price_gteq)}  

Controller

def index    @properties = Property.where(:status=>'1')    @properties = @properties.status(params[:status]) if params[:status].present?    @properties = @properties.price(params[:price_lteq]) if params[:price_lteq].present?    @properties = @properties.price(params[:price_gteq]) if params[:price_gteq].present?  end  

when i tried like this,i got query like this

SELECT `properties`.* FROM `properties` WHERE `properties`.`status` = '1' AND (price_paisas >= '000' or price_paisas <= '000') AND (price_paisas >= '49900' or price_paisas <= '49900')  

`

what i need is active record like this

SELECT `properties`.* FROM `properties` WHERE `properties`.`status` = '1' AND (price_paisas >= '000' and price_paisas <='49900')  

How to do so. Please help. Any help is appreciable.

Rails 4 - datetimepicker-rails gem, datepicker not disabling

Posted: 25 Apr 2016 03:57 AM PDT

I am using the datetimepicker-rails gem (https://github.com/zpaulovics/datetimepicker-rails)

I would like to have a simple timepicker, but datepicker is always present. I tried with using the "format" option, the "pickDate: false" option but it is still there. What am I doing wrong?

Here is the sample of my view:

<%= simple_form_for(@hour, html: {class: 'form-inline'}, remote: true) do |f| %>  <%= f.error_notification %>  <div class="row form-inputs">    <%= f.input :start_time, as: :time_picker, autocomplete: :off %>    <%= f.input :end_time, as: :time_picker, autocomplete: :off  %>  </div>  <div class="form-buttons">    <%= f.button :submit, "Zapisz", class: "btn btn-primary" %>    <%= link_to '<button type="button" class="btn btn-primary" title="Wstecz">Wstecz</button>'.html_safe, hours_path %>  </div>  <% end %>  

and in coffee script I have

$(document).ready -> $('.time_picker').datetimepicker XXX  

where XXX was one of the options I tried: format: "H:i", format: "LT" or pickDate:false.

Thank you in advance for your help.

Regards, Paulina

1 comment:

  1. very informative blog and useful article thank you for sharing with us , keep posting Ruby on Rails Online Training Hyderabad

    ReplyDelete