Wednesday, August 3, 2016

Ruby on Rails - undefined local variable or method - wice grid haml show_code | Fixed issues

Ruby on Rails - undefined local variable or method - wice grid haml show_code | Fixed issues


Ruby on Rails - undefined local variable or method - wice grid haml show_code

Posted: 03 Aug 2016 07:53 AM PDT

I am new to ruby on rails.

I am trying to get haml and wice_grid to work together. I am using this example as a model:

http://wicegrid.herokuapp.com/basics3

I get the error 'undefined local variable or method `show_code' for...'

In the file app/views/basics3/index.html.haml which you can see at the link above.

Am I missing a gem? In general, what is the best way to troubleshoot problems like this?

Thanks in advance-

Flex

Pass rails object value into span title

Posted: 03 Aug 2016 07:53 AM PDT

I want to be able to pass an object value into the title of a span element however when I use the below code on hover #{campaign.status} is displayed rather than Aprroved or Rejected as is my intention.

%td.status-data= campaign.status == "Approved" ? '<span title="#{campaign.status}" class="glyphicon glyphicon-ok green center"></span>'.html_safe : campaign.status == "Rejected" ? '<span title="#{campaign.status}" class="glyphicon glyphicon-remove red center"></span>'.html_safe : campaign.status  

Submitting a form using jquery doesn't submit it as remote: true rails 4.2

Posted: 03 Aug 2016 07:52 AM PDT

I have to submit a form when user clicks a button for that I'm using an onclick JS function call on that button.

In that function, I simply submit the form I want using .submit() function.

JS function I use,

$('#form_id').submit()  

Also in the form_tag I've used :remote=>true. The HTML method has been changed to post using :method=> "post".

Controller also has proper respond_to block with format.js block.

View file has proper .js.erb file.

But whenever I click the button it is being processed as HTML. If I manually click on that form's submit button it's processed as JS successfully.

How to fix the issue??

Rails 4: Stop redirect after create or update form

Posted: 03 Aug 2016 07:44 AM PDT

Someone know how can I do to Rails do not redirect to other page when I create or update a form?

This is because I'm using remote: :true to update the form by ajax.

def create     @picture = Picture.new(picture_params)    respond_to do |format|    if @picture.save      #format.html { redirect_to @picture, notice: 'Picture was successfully created.' }      format.json { render :show, status: :created, location: @picture }    else      format.html { render :new }      #format.json { render json: @picture.errors, status: :unprocessable_entity }    end  end  

end

<%= form_for(@picture, remote: :remote, :authenticity_token => true, html: { multipart: true } ) do |f| %>  

[...]

<%= f.submit 'Enviar', remote: :true %>  

If I just remove the redirect function I get the error:

ActionController::UnknownFormat   

Thanks!

Ruby: http POST with nested params not working

Posted: 03 Aug 2016 07:47 AM PDT

I am trying to do Http Basic Authentication with POST and nested parameters. While the outer parameters work fine (class.name - ActionController::Parameters) the nested parameters are string (class.name - String) Here is my code ->

require 'net/http'    uri = URI('http://example.com/bulb/')  req = Net::HTTP::Post.new(uri)  req.basic_auth 'mytest@somesite.com', 'mypassword'    req.set_form_data('first_params' => 'a', 'seconnd_params'=>'b', 'netsed_params'=>{'first_netsed'=>'c', 'second_nested'=>'d'}, 'commit'=>'Create Bulb', 'action'=>'create', 'controller'=>'bulb')    res = Net::HTTP.start(uri.hostname, uri.port) do |http|    http.request(req)  end    case res  when Net::HTTPSuccess, Net::HTTPRedirection    # OK    else    #failed  end  

What other library can I use to make the nested params work without having to manually convert them. I see that set_form_data doesn't work with nested hash

Heroku db:setup returns ECONNREFUSED: connect ECONNREFUSED 50.ipaddress:5000

Posted: 03 Aug 2016 07:23 AM PDT

Was making my first rails app and after pushing files to heroku, tried to run the db setup, but it dies with this message:

ECONNREFUSED: connect ECONNREFUSED 50.ipaddress:5000

Is it my/server firewall causing this? What can be done? Any kind of help is really appreciated.

Here are heroku logs

2016-08-03T14:15:23.910432+00:00 heroku[api]: Starting process with command `bundle exec rake db:setup` by useremail  2016-08-03T14:15:27.606269+00:00 heroku[run.3204]: Awaiting client  2016-08-03T14:15:27.749269+00:00 heroku[run.3204]: State changed from starting to up  2016-08-03T14:15:57.614216+00:00 heroku[run.3204]: Error R13 (Attach error) -> Failed to attach to process  2016-08-03T14:15:57.614216+00:00 heroku[run.3204]: Process exited with status 128  2016-08-03T14:15:57.625775+00:00 heroku[run.3204]: State changed from up to complete  

Rails 3: url helper always raise errors in models or console, but work fine in controllers/views

Posted: 03 Aug 2016 07:49 AM PDT

To be clear, I can call these url_helpers, and what I tried works fine on other projects: it's not an include issue.

A simple Rails.application.routes.url_helpers.root_path (or any other route) will throw ActionController::RoutingError: No route matches ... if called from a model, rails console or a view rendered with render_to_string, but the same root will work fine in a controller or view rendered the usual way.

Calling a model method using url_helpers from a view or a controller will also raise the same exception, so I don't think it's due to the lack of request.

The project is using rails 3.0, and what I tried works fine on other rails 3.0 projects.
Would you have any idea where to look to solve this?

GRAPE API + Interactors + current_user

Posted: 03 Aug 2016 07:19 AM PDT

How to enable 'current_user' in grape controllers? I'm using interactor gem and I'm going to 'create Item' with 'user id' param. I want to associate Item with current_user: item.user_id = current_user.id. How to do that?

What is the use of active type gem & nested attributes in rails?

Posted: 03 Aug 2016 07:13 AM PDT

I have five models named as(user,load,load_types,truck_types,company) from this i would like to create one controller name as load acquisition without a model.Here i want's to use the gem active_type and nested attribute concept for create&updating process. My fields in above four table.

load_type_id-->loadtypetable  load_pick_from_date-->loadtable  load_pick_to_date-->loadtable  negotiated_price-->loadtable  source-->loadtable  destination-->loadtable  remark-->loadtable  truck_type_id-->truck_typetable  company_name-->companytable  email->usertable  landline_no->usertable  mobile_no->usertable  name->usertable  

How to use the active_type gem in my rails app with nested attributes concepts.

How to match multiple patterns with Dir.glob?

Posted: 03 Aug 2016 06:54 AM PDT

In my Rails app I am trying to collect the paths to all the files contained in two different directories using Dir.glob.

The following code works but is not very concise. Isn't there a way two match two patterns at once with Dir.glob?

common_file_paths = Dir.glob("app/assets/mystuff/*").reject do |path|    File.directory?(path)  end    more_file_paths = Dir.glob("app/assets/mystuff/more/*").reject do |path|    File.directory?(path)  end    file_paths = common_file_paths + more_file_paths  

Rails content_tag method

Posted: 03 Aug 2016 07:13 AM PDT

I was browsing the source code of this gem and I found a use of content_tag that confuses me a lot.

def render(view)    view.content_tag(name, attributes[:content], attributes.except(:content))  end  

I do not understand why content_tag is called on view. I generally use it as helper to generate HTML tags, but I've never called it as a method.

Rails - Need rails reports [on hold]

Posted: 03 Aug 2016 06:31 AM PDT

I have two models Tourists and Country and i need following queries. I have has_many :tourists and belongs_to :country assocations.

Highest num of tourists traveled from which country    Highest num of tourists traveled on which month     Highest num of tourists traveled on which age group  

Ruby on Rails adding PDFs to partials

Posted: 03 Aug 2016 06:17 AM PDT

I have a rails form that a user fills out, and later they can print it off as a PDF. The content is very similar (removed navbar and links, etc).

Now I need to add PDF documents at specific locations of the PDF version of the form.

For example, take a form for a rental application that has the property details, first tenant details, pdf document, followed by a second tenants details, another pdf document.

I'm currently using PDFkit to generate PDFs from html. But I'm open to suggestions.

Thanks,

Rails search table clickable link

Posted: 03 Aug 2016 07:21 AM PDT

I have a keyword search page for which the results are presented in a table. One of the fields in this table is a url which I want to display as a clickable link when the field has one in it but I can't get this working, when the link is clicked it instead queries the search again. I think the problem is due to the def within the searches controller dealing with the keywordsearch view. Can anybody help?

Below is the keywordsearch view which contains the results table:

<!-- Index of all Courses -->  <% provide(:title, "Courses Page") %>      <!--Breadcrumbs -->  <br>  <%= link_to "Back", :back %><br><br>    <!--Page Contents -->         <div class ="row">      <h1>Degrees Offered</h1>      <%= image_tag "line.png" , :alt => "line break"%>        </div>      <div class ="row">          <!-- Form for Keyword Search, to Querry Database for University courses. It is hidden so as to not appear as a search on the page -->        <div class = "hidden">                 <%= form_tag(keywordsearch_path, :method => "get", id: "search-data") do %>        <%= text_field_tag :search, params[:search], placeholder: "Search course" %>        <%= submit_tag "Search" %>        <% end %>        </div>             <% if @search_degree != nil %>        <% end %>          <% if @search_degree != nil %>          <table border="1" class="table">            <thead>              <tr>                <th>University Name</th>                <th>Course Name</th>                <th>Duration</th>                <th>Qualification</th>                <th>Entry Requirements</th>                <th>Course Page</th>              </tr>            </thead>            <tbody>              <% @search_degree.each do |degree| %>              <tr>                <td><%= degree.uname %></td>                <td><%= degree.cname %></td>                <td><%= degree.duration %></td>                <td><%= degree.qualification %></td>                <td><%= degree.entry %></td>                <td> <a href=<% degree.url %>>View course page on University Website</a></td>              </tr>              <% end %>            </tbody>          </table>        <% end %>      </div>  

Below is portion of the search controller in which keyword search is defined:

  def keywordsearch      @search = Degree.all.select(:uname, :cname, :ucas, :duration, :qualification, :entry).distinct.order(id: :ASC)      if params[:search]        @search_degree = Degree.search(params[:search]).order('uname ASC')      end    end  

The link from all of this is clickable but rather than taking me to the correct url it redoes the search.

logrotate appending the date to logs in wrong way

Posted: 03 Aug 2016 05:58 AM PDT

I have a rails application and I have setup logrotate for the logs. The logs are like production.log, sidekiq.log, cron.log in the directory /home/username/myapp/log/. I want the rotated logs should be named like production.log-server-1-2016-08-02-1470119678.gz. This type of file is also present but one more file is there which is named like production.log-server-1-2016-08-02-1470119678.gz-server-1-2016-08-03-1470206339-server-1-2016-08-03-1470225672.gz.

Below are my configuration for logrotate

/etc/logrotate.d/myapp

/home/user/myapp/log/*.log {      weekly      size 10M      missingok      rotate 7      compress      delaycompress      copytruncate      #create 0640 ubuntu ubuntu      su ubuntu ubuntu      sharedscripts      prerotate        endscript      postrotate        endscript  }  

/etc/logrotate.conf

# see "man logrotate" for details  # rotate log files weekly  daily  size 10M  # use the syslog group by default, since this is the owning group  # of /var/log/syslog.  su root syslog    # keep 4 weeks worth of backlogs  rotate 4    # create new (empty) log files after rotating old ones  create    # use date as a suffix of the rotated file  dateext  dateformat -server-1-%Y-%m-%d-%s    # uncomment this if you want your log files compressed  compress    # packages drop log rotation information into this directory  include /etc/logrotate.d    # no packages own wtmp, or btmp -- we'll rotate them here  /var/log/wtmp {      missingok      weekly      size 500K      create 0664 root utmp      rotate 1  }    /var/log/btmp {      missingok      weekly      size 500K      create 0660 root utmp      rotate 1  }    # system-specific logs may be configured here  

Any help? Basically I want the log file should be named like production.log-server-1-date-month-year-time.gz and it should be rotated if the file size increases more than 10mb or weekly.

How to search one column in searchkick

Posted: 03 Aug 2016 06:31 AM PDT

I'm trying to just search one column. (to adapt upon in the future to search dates and location and event type)

I'm using searchkick, Which works lovely however i can search the location when all i want is the event name passed back, However i'm wanting to use the location and others later on. Any help would be great!

Any ideas? Sam

TinyTDS: Server name not found in configuration files

Posted: 03 Aug 2016 07:48 AM PDT

I keep seeing this error, and I am unable to connect to the database on the remote server.

I am given a connection string to the database, that looks like the following:

data source=qsss.gar.de\SQL2012,3000;initial catalog=City;persist security info=True;user id=user_me;password=user_me##2009;  

Now, I have created a database.yml file based on that connection string, like the following:

development:      adapter:  'sqlserver'      host:     'qsss.gar.de\SQL2012,3000'      port:     1433      database: 'City'      username: 'user_me'      password: 'user_me##2009'  

And as I try and run the server, it always hits me with the Server name not found in configuration files error.

opts[:port] ||= 1433        opts[:dataserver] = "#{opts[:host]}:#{opts[:port]}" if opts[:dataserver].to_s.empty?        connect(opts) // ERROR AT THIS LINE      end        def tds_73?  

Please try and help me figure what is the problem with this?

UPDATE:

I can connect to the server using SQLPro for MSSQL wizard, with exactly the same connection parameters:

picture

It works from the wizard, but not from code using TinyTDS!

What does yield do in this Ruby method?

Posted: 03 Aug 2016 05:52 AM PDT

I have a bit of old code in a legacy app which uses yield in a way that I don't understand. I could use some help with an explanation. I've read most of the SO results on Ruby yield but don't understand it in this context. Thanks.

def find_all_from_source(source_id, some_more_arguments)    joins, conditions = invoke_records_from_source(source_id, some_more_arguments)    find(:all, :select => "#{self.table_name}", :joins => joins, :conditions => conditions).each do |record|      yield record    end  end    model.find_all_from_source(source_id, some_more_arguments)  

rails5 doorkeeper+devise, return invalid_redirect_uri error

Posted: 03 Aug 2016 05:23 AM PDT

I want to use doorkeeper and devise to be the single user service. So I create server-app and client-app.

When I click Authorize button and will redirect to callback uri http://localhost:3001/users/auth/doorkeeper/callback and in client I get

   [2016-08-03T20:03:53.196488 #9843] ERROR -- omniauth: (doorkeeper)  Authentication failure! invalid_credentials: OAuth2::Error, invalid_redirect_uri: The redirect uri included is not valid.  {"error":"invalid_redirect_uri","error_description":"The redirect uri included is not valid."}  

I tried many times and watch others example apps , but I don't know why.

Server-app Gemfile

        source 'https://rubygems.org'  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '~> 5.0.0'  # Use sqlite3 as the database for Active Record  gem 'sqlite3'  # Use Puma as the app server  gem 'puma', '~> 3.0'    gem  'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.2'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'      # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks  gem 'turbolinks', '~> 5'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.5'  # Use Redis adapter to run Action Cable in production      # gem 'redis', '~> 3.0'  # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    gem 'doorkeeper', '4.0.0.rc4'  gem 'doorkeeper-i18n'  gem 'devise'  gem 'oauth2'  gem 'omniauth'    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug', platform: :mri  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.    gem 'web-console'    gem 'listen', '~> 3.0.5'    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

```

doorkeeper.rb ```

Doorkeeper.configure do    # Change the ORM that doorkeeper will use (needs plugins)    orm :active_record      # This block will be called to check whether the resource owner is authenticated or not.    resource_owner_authenticator do      current_user || warden.authenticate!(scope: :user) ||        (user = User.find_for_database_authentication(email: params[:username])          if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }            user          end)      end      resource_owner_from_credentials do |routes|      user = User.find_for_database_authentication(email: params[:username])      if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }        user      end    end        # If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below.    # admin_authenticator do    #   # Put your admin authentication logic here.    #   # Example implementation:    #   Admin.find_by_id(session[:admin_id]) || redirect_to(new_admin_session_url)    # end      # Authorization Code expiration time (default 10 minutes).    authorization_code_expires_in 100.minutes      # Access token expiration time (default 2 hours).    # If you want to disable expiration, set this to nil.    access_token_expires_in nil      reuse_access_token      # Issue access tokens with refresh token (disabled by default)    use_refresh_token      native_redirect_uri 'urn:ietf:wg:oauth:2.0:oob'      # Forces the usage of the HTTPS protocol in non-native redirect uris (enabled    # by default in non-development environments). OAuth2 delegates security in    # communication to the HTTPS protocol so it is wise to keep this enabled.    #    force_ssl_in_redirect_uri false #!Rails.env.development?      grant_flows %w(authorization_code client_credentials)      end  Doorkeeper.configuration.token_grant_types << 'password'    ```    -----------------------------------  

client-app gemfile

```  rails 5   gem 'omniauth'  gem 'omniauth-oauth2'  ```  

devise.rb ``` config.omniauth :doorkeeper, '62ec3482b200c919d8f8b4200b835750fa1350b73c1738fc2eeb7aba853c27eb', '01bf2d73fa35dd96284dd029bd8151e0862382b2874737e83c1419fc693dd010'

```    doorkeeper.rb  ```ruby  require 'omniauth-oauth2'    module OmniAuth    module Strategies      class Doorkeeper < OmniAuth::Strategies::OAuth2        # change the class name and the :name option to match your application name        option :name, :doorkeeper          option :client_options, {                                :site => "http://server.qdaily.com:3010",                                :authorize_url => "http://server.qdaily.com:3010/oauth/authorize",                                :token_url => "http://server.qdaily.com:3010/oauth/token"                              }          option :provider_ignores_state, true          uid {  raw_info['id'] }          info do          {            :email => raw_info["email"]            # and anything else you want to return to your API consumers          }        end          def raw_info          @raw_info ||= access_token.get('/api/users/1/me').parsed        end      end    end  end  ```  

Twilio Say when putting conference on hold

Posted: 03 Aug 2016 05:47 AM PDT

I am able to put the conference call on hold, but I would like Twilio to say something like 'This call has been put on hold' to all participants before the music starts playing.

I've been trying to do something like this, but it's not working:

response = Twilio::TwiML::Response.new do |r|      # Loop over participants and print out a property for each one    @client.account.conferences.get(@conference_sid).participants.list.each do |participant|      participant.update(:hold => false) if !params[:hold]      if params[:hold]        participant.update(:hold => true)        r.Say 'This call has been put on hold.'      end    end  end  

Anyone know how to achieve this? Thanks.

spaghetti code - how to fix my db calls

Posted: 03 Aug 2016 05:16 AM PDT

My db calls are like this:

orders_pending_acceptance = Order.joins(:notifications).includes(:timestamps)      .where(shopper_status: 'shopper_pending_acceptance')      .where("notifications.created_at > ?", now - 10.minutes)      .select { |order| order.time_calculator        .latest_shopper_assignment_time < order.timestamps        .where(name: 'shopper_pending_acceptance').value }  

and it looks ugly, not speaking about hound issues. How to fix it? Could you please suggest different approach?

Ruby Mysql2 Client not taking backslash while insert

Posted: 03 Aug 2016 07:27 AM PDT

We are using production and staging databases in our application. Our requirement is to insert all the records to staging database when ever a record is added in production database, so that both the servers are consistent and same data.

I have used Mysql2 client pool to connect to staging server and insert the record that is added to production. here is my code:

def create         @aperson = Person.new      @person = @aperson.save      if @person && Rails.env == "production"        #add_new_person_to_staging          client = Mysql2::Client.new(:host => dbconfig[:host], :username => dbconfig[:username], :password => dbconfig[:password], :database => dbconfig[:database])                @person_result = client.query('INSERT INTO user_types(user_name,    regex, code) Values ("myname" , "\.myregex\." , "ns" );')      end  end  

Here "@person_result" record is inserted to mysql table but the "regex" column eliminates "\" slashes.

like : user_name = myname, regex = .myregex., code = ns

when I manually execute the "Insert" query in mysql command line it inserts as it is along with \ slash. but not through "client.query" Why does \ slash is eliminated. please help me here.

Thanks.

Rails query execution causes database spikes

Posted: 03 Aug 2016 05:05 AM PDT

I'm having a problem with my Rails application where some random queries take around 5 seconds or longer to finish. Most of the time the queries are very simple (select * from x where id = ?) and the fields are even indexed too.

Here's some more information about the setup:

  • Puma 3.5.0 behind a reversed nginx proxy
    • 4 workers with minimum 4, max 8 threads each.
  • Ruby v2.2.3, Rails v4.2.4
  • PostgreSQL 9.4 database
    • Thread pool set to max 60 connections
  • Appsignal for monitoring
  • 8GB RAM, 4 CPU's, SSD.

I found this out when looking at the query performance in Appsignal. I noticed most queries finishing in a few ms and then every now and then, still in the same request, there are multiple queries that take 5+ seconds to finish. And the odd part is that it ALWAYS takes 5,.. seconds. Here's a picture of that in action: Appsignal performance

Things I've tried:

  • Increase the thread pool to make sure the puma worker threads have enough connection objects.
  • Set 'reaping_frequency' to 10s to make sure there are no dead connections being used.
  • Increase puma workers/threads

I'm noticing this in the application as there are some pages that take a long time to load (I have a function call that takes about 1 minute to finish) and somehow this is blocking new requests. This is strange to me as there are 4 workers each with 8 threads = 32 threads that can handle the other requests.

Multiple addresses in rails geocoder issue

Posted: 03 Aug 2016 06:40 AM PDT

I have a booking model with location_pickup and location_dropoff on which i want to use the geocoder feature. I have declared the geocoder mapping in the model (below), but somehow only the last declaration(location_pickup) is getting updated in the database. Anything specific I am doing wrong here?

class Booking < ActiveRecord::Base  belongs_to :user    geocoded_by :location_dropoff, :latitude => :location_dropoff_latitude,   :longitude => :location_dropoff_longitude    geocoded_by :location_pickup, :latitude => :location_pickup_latitude, :longitude => :location_pickup_longitude    after_validation :geocode, if: :location_dropoff_changed?  after_validation :geocode, if: :location_pickup_changed?    validates :location_pickup, presence: true  validates :location_dropoff, presence: true  end   

OpenSSL::SSL::SSLError hostname does not match the server certificate rails 2

Posted: 03 Aug 2016 04:41 AM PDT

I'm trying to make an API call to SmartDebit a 3rd party direct debit processing website from my Ruby 1.9.3, Rails 2 app.

I'm getting this error:

OpenSSL::SSL::SSLError·hostname does not match the server certificate  

The error occurs here: "https://onepointnine.survivalinternational.org/donate" when trying to make a direct debit payment.

As far as I can tell my SSL certificate is correctly set up and valid for this hostname, Smart Debit have confirmed that the error doesn't refer to their endpoint.

Also, the error can't be to do with certificate verification because I already have this code in an initializer (n.b. I realise this isn't best practice, I've inherited this codebase):

class Net::HTTP    alias_method :old_initialize, :initialize    def initialize(*args)      old_initialize(*args)      @ssl_context = OpenSSL::SSL::SSLContext.new      @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE    end  end  

Any idea what's wrong?

rails Cannot nest nested form with parent form in index page

Posted: 03 Aug 2016 04:55 AM PDT

index.html.haml

I have to display customer detail list in index page.I want the nested form 'goods address' fields also to be listed in index page

%tbody          - @customer_details.each do |customer|            %tr              %td= customer.customer_name              %td= customer.customer_id              %td= customer.address              %td= customer.state              %td= customer.email                - customer.goods_address.each do |goods_address|                  %td= goods_address.delivery_address                  %td= goods_address.name                  %td= goods_address.address                  %td= goods_address.state
The problem is im getting undefined method 'each' for goods address. I dont know how to solve this. can someone help me.Thanks in advance

Typhoeus - Couldn't connect to server

Posted: 03 Aug 2016 04:27 AM PDT

I have a typhoeus call like so in my rails app -

Typhoeus::Request.get("http://abcd.data_center1/v1/return.json"), which works fine.

Now we are migrating the code to a new datacenter

but for this endpoint we want to still use the same datacenter as above.

When hitting the above with typhoeus I get -

but I am able to ping the endpoint just fine.

What could be the issue here?

TIA

Rails - devise and sidekiq routes

Posted: 03 Aug 2016 04:40 AM PDT

I am running a Rails 5.0.0 app with Ruby 2.3.1

Sidekiq is being used for background jobs and devise for authentication.

Sidekiq monitoring and devise are mounted in routes as follows:

devise_for :users, skip: [:sessions]      as :user do          get    'login' => 'devise/sessions#new',      :as => :new_user_session          post   'login' => 'devise/sessions#create',   :as => :user_session          delete 'logout' => 'devise/sessions#destroy', :as => :destroy_user_session      end    require 'sidekiq/web'      require 'sidekiq/cron/web'      #Sidekiq::Web.set :session_secret, Rails.application.secrets[:secret_key_base]      authenticate :user do          mount Sidekiq::Web => '/sidekiq'      end  

But, accessing the sidekiq status page logs out the user.

The same code used to work fine with Rails 4.2.5

Route to Current User Edit in a view

Posted: 03 Aug 2016 05:45 AM PDT

What is the syntext I need to use in order to route to edit the current user's profile? I want to put a link on my page that takes you to edit your user profile. I know how to link_to but not sure what what the syntex is to get to the current user.

My Users controller looks like this:

class UsersController < ApplicationController    before_action :logged_in_user, only: [:index, :edit, :update, :destroy]    before_action :correct_user,   only: [:edit, :update]    before_action :admin_user,     only: :destroy        def index      @users = User.paginate(page: params[:page])    end      def new      @user = User.new    end      def create      @user = User.new(user_params)        if @user.save          flash[:notice] = "Welcome to Studio Academy Manager"        sign_in @user          redirect_to root_url      else          render 'new'      end    end      def show      @user = User.find(params[:id])    end      def edit      @user = User.find(params[:id])    end      def update      @user = User.find(params[:id])      if @user.update_attributes(user_params)        flash[:success] = "Profile updated"        redirect_to @user      else        render 'edit'      end    end      def destroy      User.find(params[:id]).destroy      flash[:success] = "User deleted"      redirect_to users_url    end    private    def user_params      params.require(:user).permit(:email, :username, :password, :password_confirmation, :first_name, :last_name, :phone, :street_1, :street_2, :city, :state, :zip, :enabled, :admin)    end      def logged_in_user    unless current_user.present?        store_location        flash[:danger] = "Please log in."        redirect_to login_url      end    end      def correct_user      @user = User.find(params[:id])      redirect_to(root_url) unless @user == current_user    end      def admin_user      redirect_to(root_url) unless current_user.admin?    end  end  

And In my routes file I have:

  resources :users  

Prawn Rails, generate table with some content not bound by table

Posted: 03 Aug 2016 04:14 AM PDT

I am trying to build a fairly complex pdf using Prawn in Rails.

The document I am trying to generate is a form of script split into four columns. The script is comprised of a collection of 'snippets', which are iterated through and populate the third column. If a snippet has special properties it can also populate any one of the other three columns as well. This is all achieved very easily using tables. However, I then need to be able to draw an arrow of some description (using prawn graphics) at certain points spanning between the table columns (please see attached image).

demo table

How is this achieved since content is bound by table cells? Is there a way to later draw these lines using cursor points or some other method?

Please ask for further for clarification if I'm not making any sense.

Thanks

No comments:

Post a Comment