Saturday, April 23, 2016

Rails log file: No route matches [PROPFIND] "/webdav" (after Ubuntu server upgrade) | Fixed issues

Rails log file: No route matches [PROPFIND] "/webdav" (after Ubuntu server upgrade) | Fixed issues


Rails log file: No route matches [PROPFIND] "/webdav" (after Ubuntu server upgrade)

Posted: 23 Apr 2016 07:41 AM PDT

I have just updated a Ubuntu server to the latest version (Ubuntu 16.04 LTS, Xenial Xerus) and am now seeing strange requests (such as Started PROPFIND "/webdav/") in my application log file:

...  I, [2016-04-23T12:30:34.499679 #4572]  INFO -- : [3bd03634-6b1e-44b2-8f51-e52c29aaf9c9] Started PROPFIND "/webdav/" for 192.99.144.140 at 2016-04-23 12:30:34 +0200  F, [2016-04-23T12:30:34.500819 #4572] FATAL -- : [3bd03634-6b1e-44b2-8f51-e52c29aaf9c9]     F, [2016-04-23T12:30:34.500872 #4572] FATAL -- : [3bd03634-6b1e-44b2-8f51-e52c29aaf9c9] ActionController::RoutingError (No route matches [PROPFIND] "/webdav"):  ...  

I have no idea where that comes from and what it means. Do you?

Attributes in DB using active records not updated even when save gives no errors in Rails

Posted: 23 Apr 2016 07:38 AM PDT

My codes are relatively simple.

    if params[:job][:payment_method_token] == "cash"       @job.payment_type = :cash      else       @job.payment_type = :credit_card      end        @job.save  

Saving did not give any errors and returns true. I have used byebug and have verified that it did go into the else block and executed the @job.payment_type = :credit_card. Unfortunately, when i check @job.payment_type, it returns "cash". How is it possible that saving doesn't return errors but yet the attribute is not updated? Really appreciate the help. Thank you.

Rails 5, Route declare but not found

Posted: 23 Apr 2016 07:24 AM PDT

In my routes config i have:

constraints subdomain: 'api' do      scope module: 'api' do          namespace :v1 do              get '/me', to: 'users#me'          end      end  end  

bin/rake routes return

v1_me GET    /v1/me(.:format)     api/v1/users#me {:subdomain=>"api"}  

When i try the uri http://localhost:3000/v1/me, http://localhost:3000/api/v1/me or http://localhost:3000/me with postman i have a 404 not found error.

 ActionController::RoutingError (No route matches [GET] "/v1/me"):  

What is wrong with my code ?

Rails filter data with multiple time period

Posted: 23 Apr 2016 06:44 AM PDT

I want let my user to decide what time period does some contents can be present.

it's divide into two partial:  1.for date (like 2016,01,01~2016,12,20)  2.for hour (like 11:00~13:00)  

there is multiple time period setting that user can add for their contents, for example

  • 11:00~12:00
  • 17:00~19:00
  • 2016,03~2016,07
  • 2017,01,20~2017,01,22

how can I implement it? add a associated table with four time columns(start date, end date, start time, end time) for contents table?? or any helpful gem?

MiniTest::Assertions returning false for test that should be returning true

Posted: 23 Apr 2016 07:24 AM PDT

I am attempting to learn MiniTest and by doing so I have started testing one of my applications that uses the PayPal API to approve/deny credit-card payments. Below is my attempt at testing the purchase method inside the Payment class. (credit_card was originally a private method, moved to public for testing)

payment.rb

require "active_merchant/billing/rails"    class Payment < ActiveRecord::Base    belongs_to :order    attr_accessor :card_number, :card_verification      def purchase(card_info, billing_info)      if credit_card(card_info).valid?        response = GATEWAY.purchase(price_in_cents, credit_card(card_info), purchase_options(billing_info))        @paypal_error = response.message        response.success?      end    end      def price_in_cents      (@total.to_f * 100).round    end          def credit_card(card_info)        @credit_card ||= ActiveMerchant::Billing::CreditCard.new(card_info)      end      private      def purchase_options(billing_info)      billing_info    end    end  

payment_test.rb

require 'test_helper'  require "active_merchant/billing/rails"    class PaymentTest < ActiveSupport::TestCase    setup do      @card_info = {        brand: "Visa",        number: "4012888888881881",        verification_value: "123",        month: "01",        year: "2019",        first_name: "Christopher",        last_name: "Pelnar",      }      @purchase = Payment.new    end      test "purchase" do      assert @purchase.credit_card(@card_info).valid?, true    end    end  

Error message after running rake test:

--------------------------  PaymentTest: test_purchase  --------------------------     (0.1ms)  ROLLBACK    test_purchase                                                   FAIL (0.02s)  Minitest::Assertion:         true          test/models/payment_test.rb:20:in `block in <class:PaymentTest>'      Finished in 0.03275s  1 tests, 1 assertions, 1 failures, 0 errors, 0 skips  

ruby-oci8 installation error in mac (El Capitan)

Posted: 23 Apr 2016 06:28 AM PDT

I'm trying to install ruby-oci8 (mac) using ruby-oci8 and unable to install.

When i try to install this gem.

gem install ruby-oci8  

Its generate error for environment variable. I am unable to figure out this problem.

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /Users/tayyab/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160423-11068-8lu6zg.rb extconf.rb  checking for load library path...   *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/Users/tayyab/.rbenv/versions/2.2.3/bin/$(RUBY_BASE_NAME)      --with-instant-client      --without-instant-client  /Users/tayyab/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.2.1/ext/oci8/oraconf.rb:566:in `check_ic_dir': RuntimeError (RuntimeError)      from /Users/tayyab/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.2.1/ext/oci8/oraconf.rb:316:in `get'      from extconf.rb:22:in `<main>'    DYLD_LIBRARY_PATH is not set.    checking DYLD_FALLBACK_LIBRARY_PATH...      checking /Users/tayyab/lib... no      checking /usr/local/lib... no      checking /lib... no      checking /usr/lib... no    checking OCI_DIR...  ---------------------------------------------------  

Error Message:

  Set the environment variable DYLD_LIBRARY_PATH, DYLD_FALLBACK_LIBRARY_PATH or    OCI_DIR to point to the Instant client directory.      If DYLD_LIBRARY_PATH or DYLD_FALLBACK_LIBRARY_PATH is set, the environment    variable must be set at runtime also.      If OCI_DIR is set, dependent shared library paths are checked. If the checking    is passed, ruby-oci8 works without DYLD_LIBRARY_PATH or DYLD_FALLBACK_LIBRARY_PATH.      Note: OCI_DIR should be absolute path.    Note: DYLD_* environment variables are unavailable for security reasons on OS X 10.11 El Capitan.  

Any idea how to resolved it?

Ruby on rails : syntax error, unexpected keyword_end, expecting end-of-input

Posted: 23 Apr 2016 06:18 AM PDT

Can somebody tell me where are the errors in this code ?

I have been searching for a while, but I still don't manage to find the mistake.

class BooksController < ApplicationController    def index       @books = Book.all       @categories = Category.all    end      def create       Book.create title: params[:title], category_id: params[:category_id]       redirect_to "/books"    end      def show      @book = Book.find(params[:id])    end      def update      @book = Book.find(params[:id])      if @book.update title: params[:title]        redirect_to "/books/#{params[:id]}"      else        render 'show'      end    end      def destroy      Book.find(params[:id]).destroy      redirect_to "/books"    end   end  

Rails consuming webservices for authentication (login)

Posted: 23 Apr 2016 07:02 AM PDT

I am looking some way to consume a internal webservices for authentication (login) in a rails app. I had used devise before but devise use it on backend database to manage the user db, also the devise extentions connect to a specific webservices for auth like Facebook, Twitter or OpenID. In this case we have a internal web services to do the auth. https://github.com/plataformatec/devise/wiki/Extensions

So we need to only manage the call and the session management in the web app. the question is exist any api that allow me to do this? integrate a custom webservices auth with my webapp for login and session purpose.

Error when making an email sending page in web app, rails. What to put in Routes.rb

Posted: 23 Apr 2016 07:32 AM PDT

I'm learning rails and have started to make an app but in the app have a way to send an email. But when I click on submit it I get an No route matches [POST] "/path" error and I have no idea what this means, I haven't put anything in the routes.rb file, should I have done?

So the main question is what needs to go into the routes file so that the email is sent and I no longer get an error

Also I have it in a file which doesn't have a model, is that bad? Could that be why this doesn't work?

Here is my code.

In Controller:

def email    @current_nav_identifier = :email      def path      data = params[:body]      user = params[:emailadd]      subject = params[:subject]      Mailer.mail_method(data,user,subject).deliver      redirect_to :home    end  end  

For Form:

= form_tag '/path' do   Email :   = text_field_tag 'email', ''   subject:   = text_field_tag 'subject', ''   Body:#{text_area_tag 'body', ''}   \#{submit_tag "submit",:value => "submit"}  

Mailer:

class InviteMailer < ApplicationMailer    def mail_method(data,email,subject)      @body=data      mail(to: email, subject: subject)    end  end  

Do I need to make the page in its own folder? so it has it has its own controller and model?

Have I missed something very simple? Any help will be most welcome.

Thanks

Rails, Arel, Ransack: sort_by sum of relation

Posted: 23 Apr 2016 07:41 AM PDT

class Document    has_many :lines  end    class Line    belongs_to :document  end    sort_by @q, :total  

Hello, I need to sort documents by the sum of their lines (amount column in lines).

I thought about a ransacker but how to write it properly?

ransacker :total do    parent ???  end  

Rails with google maps. TypeError: a is null

Posted: 23 Apr 2016 07:05 AM PDT

I have a ruby on rails application in which in 80% of the pages I am using google maps. So in many of my seperate JS files (in assets/javascripts) I have included many variables from google like

google.maps.DirectionsStatus  new google.maps.LatLng(a,b)  new google.maps.Marker  google.maps.event.addListener  

And I have included the below script in my application.html.erb in head section

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<%= ENV["GOOGLE_MAP"]%>&sensor=false&libraries=places">  </script>  

In production in pages in which I am not using google maps an error is displayed on console

TypeError: a is null  

...(null,_.ia)},p$=function(a,b){this.j=a;this.ma=a.value;this.Vd(this.ma);this.V=b...

This stops other javascript functions in the pages with no google maps from running.Everything in the localhost works fine btw its only in production (Aws-ec2 server with ubuntu. Server nginx and app server puma) that it is not working. Have I gone wrong with google maps integration? Is there a workaround for this problem?

Note: I am not using turbolinks for the application.

Update: Upon further testing only document.ready functions are not working on such pages. Other js functions on such pages are working fine in production.

Why does my date object have methods for Sunday and Monday, but not the other days of the week?

Posted: 23 Apr 2016 06:40 AM PDT

Can anyone explain the following behavior?

date = Date.today  # => Sat, 23 Apr 2016  date.sunday  # => Sun, 24 Apr 2016  date.monday  # => Mon, 18 Apr 2016  date.tuesday  # => NoMethodError: undefined method `tuesday' for Sat, 23 Apr 2016:Date  Did you mean?  tuesday?  

Rails association has_many through not working with multiple models

Posted: 23 Apr 2016 04:58 AM PDT

I am a newbie to rails. I wanted to try out has_many through association with the following example.

  1. There are two types of doctors. operation_doctors and treatment_doctors.
  2. There are two types of patients. operation_patients and treatment_patients.

Relation: Operation_doctors can only make an appointment with operation patients and vice versa. Same applies for treatment doctors.

Doctor.rb

class Doctor < ActiveRecord::Base  has_many :appointments  has_many :operation_patients, :class_name => 'Patient', :source => :operation_patient ,through: :appointments  has_many :treatment_patients, :class_name => 'Patient', :source => :treatment_patient ,through: :appointments  end  

Patient.rb

class Patient < ActiveRecord::Base  has_many :appointments  has_many :operation_doctors,:class_name => 'Doctor', :source => :operation_doctor,through: :appointments  has_many :treatment_doctors,:class_name => 'Doctor', :source => :treatment_doctor,through: :appointments  end  

Appointment.rb

class Appointment < ActiveRecord::Base  belongs_to :operation_doctor, :class_name => 'Doctor', :foreign_key => :operation_doctor  belongs_to :treatment_doctor, :class_name => 'Doctor', :foreign_key => :treatment_doctor  belongs_to :operation_patient, :class_name => 'Patient', :foreign_key => :operation_patient  belongs_to :treatment_patient, :class_name => 'Patient', :foreign_key => :treatment_patient  end  

Error in Rails console: Input:

@op1 = Patient.new  @od1 = Doctor.new   

Error:

irb(main):023:0> @op1.operation_doctors << @od1  (0.1ms)  begin transaction  (0.1ms)  rollback transaction  ActiveRecord::UnknownAttributeError: unknown attribute 'patient_id' for Appointment.  

Finding the cheapest price of a combination of 2 models with a scope

Posted: 23 Apr 2016 06:03 AM PDT

I have the following Models:

class Rim < ActiveRecord::Base      has_many :wheels        scope :cheapest, -> { minimum(:price) }  end    class Tyre < ActiveRecord::Base      has_many :wheels        scope :cheapest, -> { minimum(:price) }  end    class Wheel < ActiveRecord::Base      belongs_to :rim      belongs_to :tyre  end  

Basically every rim and tyre have a price, and when you put 2 together, the price is the combination of both prices, but not all rims and tyres cam combine, so I can't simple search for the cheapest of Rim and Tyre and put them together. I have to actually go through all the entries listed on the table wheels.

How could I create a scope on Wheel to get the cheapest wheel?

Joining two ActiveRecord associations on common attribute

Posted: 23 Apr 2016 05:00 AM PDT

Let's say I have a User model. User has 2 has_many associations, that is User has many pencils and has many cars. Cars and Pencils table has same attribute, :date, and separate such as :speed(car) and :length(pencil). I want to join a user's pencils and cars on their common attribute, :date, so that I have an array/relation [:date, :speed, :length]. How do I achieve that, I tried joins and merge but they were no use.

List of available i18n translations for "helpers" in Ruby on Rails 4 and Simple Form?

Posted: 23 Apr 2016 06:13 AM PDT

I can't seem to find a documentation to list what helpers are available for Rails' i18n.

I first saw it in Simple Form's README

The closest I find is in the example here

helpers:      select:        prompt: Please select      submit:        create: Create %{model}        submit: Save %{model}        update: Update %{model}  

However, I am also aware that labels and other things are also applicable in this section.

What is the complete list of available helpers entries?

Sidebar menu not collapse/hide - bootstrap SB admin 2 (Ruby on Rails)

Posted: 23 Apr 2016 04:28 AM PDT

I'm now following instructions on this page.

I copied and imported everything needed and got the following result:

enter image description here

The menu should be hidden and show when clicked, but it's not.

Link to my project in GitHub.

Rspec - Attempting to optimize a jpeg without jpegoptim installed. Skipping

Posted: 23 Apr 2016 04:05 AM PDT

I have a model called Objective.

Following is my Factory file. Uploading a sample file from locally...

FactoryGirl.define do    factory :objective do      name { Faker::Name.name }      icon_url { Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/free-samples.jpg'))) }      description { Faker::Lorem.paragraph }    end  end  

When I am running Rspec, I am getting Attempting to optimize a jpeg without jpegoptim installed. Skipping...

Following is my objective_spec.rb

require 'rails_helper'    RSpec.describe Objective, :type => :model do      it "Should be valid with proper Name, icon_url and description" do      expect(build(:objective)).to be_valid    end  end  

Rails: Heroku PostgreSQL "free" random behaviour to database performance

Posted: 23 Apr 2016 03:49 AM PDT

Hi I recently put my app into production with Heroku and noticed that the performance on the "free" postgresql package is very unstable. I am on the free Postgresql package. Is the performance on the "standard" package really more reliable?

Example: I try to get a boolean from the user from the database to see if I have rewarded a user for a certain action. Locally this works 100% of times. On Heroku it seems that sometimes it cant find the current_user. Also it sometimes gives me a problem with loading partials.

How can I parse subpages of another website in Rails?

Posted: 23 Apr 2016 03:28 AM PDT

I'm creating a third-party web application of Last.fm and I'm having an issue with getting info about certain artist from them.

I have a method that parses data about some #{artist} from JSON:

artists_helper.rb

require 'net/http'  require 'json'    module ArtistsHelper    def about(artist)      artist = "?"      url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"      uri = URI(url)      response = Net::HTTP.get(uri)      JSON.parse(response)  end    end  

If I change '?' to the artist name in that method I can successfully parse info about artist from JSON file of that artist. But for when I go the page e.g. http://localhost:3000/artists/Wild+Nothing I need the method 'about(artist)' to get the value 'Wild+Nothing' and parse the data for Wild Nothing from Last.fm's JSON file.

How can I tell the method 'about' that what stands after http://localhost:3000/artists/ is the required value?

Window.onload not getting called [Ruby on Rails] [Vanilla Javascript]

Posted: 23 Apr 2016 03:50 AM PDT

I have a Ruby on Rails Application, with application.html.erb with the following body structure.

<Header>    <anchor tags></anchor tags>  </Header>  <%= yield %>  

On clicking the anchor tags in the header -> the content of the yield changes. But the window.onload only loads one time i.e. when the page loads for the first time, despite navigating through the anchor tags in the header. Due to which all the bindings and events which were handled inside the window.onload are getting lost.

How to add the same bindings and events when window.load is not getting called OR any alternative to window.onload using vanilla javascript that can solve the problem?

How to get signup user id in another controller in devise

Posted: 23 Apr 2016 06:20 AM PDT

user.rb

has_one :company  

My requirement is that when user sign up page is redirect to new company form. How can I get sign up user id there?

Is it possible?

What's the best way to create groups/collections of objects (of the same model) in Rails?

Posted: 23 Apr 2016 02:03 AM PDT

I have an application which asks users questions, then (depending on the answer) passes through the relevant next_question to the controller - a kind of state machine/decision tree. For one use-case I need the ability to group together a set of answers, then loop back to the beginning question of the group and start building another group following the same chain.

So far I can direct the controller to start a new chain, but the existing chain just sort of floats there, and I want to segregate it into groups. As such I've defined certain questions as "collectable" by adding a column to the DB add_column :collectable, :boolean, default: false and flagging those I want to group together by setting that column to true. This works fine.

In the model, these items are called SaleQualifiers each has_one :answer and belongs_to :question (the question model holds the collectable information). On my SaleQualifiers model I have added a column collection_id, :integer - so the plan is to use some logic that will check whether a SaleQualifier's question is collectable or not, then pass an id to the collection_id column which I'll use to group these objects in the display and in the routing logic (for e.g. editing a SaleQualifier).

How do you go about setting the id's of a column outside of the standard Rails controlled id allocation? What would be the safest way of doing this? For my purposes I probably want to give more than one SaleQualifier the id=1, because SaleQualifiers belong_to SalesOpportunities and I can scope the SaleQualifier by the parent SalesOpportunity_id.

Any recommendations?

Deployed Rails app still seeing nginx splash page

Posted: 23 Apr 2016 03:33 AM PDT

I've just set up my first Digital Ocean VPS and managed to deploy my Rails app by following this guide: https://gorails.com/deploy/ubuntu/14.04

Unfortunatley I am still seeing the nginx splash page and hoep you guys can help me fix this?

In the nginx error log I am seeing this:

[ 2016-04-20 14:48:15.4541 31875/7f70762f57c0 age/Ust/UstRouterMain.cpp:342 ]: Passenger UstRouter online, PID 31875 2016/04/21 14:58:58 [emerg] 1721#0: "listen" directive is not allowed here in /etc/nginx/sites-enabled/default.save:27

My nginx conf looks like:

server {          listen 80 default_server;          server_name dev.myapp.co.uk;          passenger_enabled on;          rails_env production;          root /home/deploy/myapp/current/public;            # redirect server error pages to the static page /50x.html          error_page   500 502 503 504  /50x.html;          location = /50x.html {              root   html;          }  }  

I obviously have changed "myapp" to my correct domain and app name as appropriate.

Any ideas?

Best practice for file upload before object is created?

Posted: 23 Apr 2016 02:30 AM PDT

I got a form that has several steps and the first one is to upload an image (via carrierwave) which is supposed to happen in the background. So the server is receiving a file for an object that doesn't exist yet. So I'm wondering what's the best practice for this case?

I thought of two approaches:

  • Make the image file a model that is created and returning the image ID upon upload completed.
  • Create the object, having validations disabled and only the image saved returning the object ID and update it afterwards with validations on.

I'm leaning towards no. 1 but maybe one of you guys have an even better idea? Not happy creating a new model just for the image.

Mongoid Rails update error for documents having embedded documents

Posted: 23 Apr 2016 01:12 AM PDT

I have a model called User. User embeds_many posts.

For User records having embedded posts, whenever I try to update any other field, I am getting the error

NoMethodError: undefined method `each' for false:FalseClass  

I am using update as follows

user = User.find('56da7307421aa90ca4000000')  user.update(likes: 12)  

If I remove embeds_many :products from User model file, the above update query works fine.

My model instance is not getting created in my controller

Posted: 23 Apr 2016 02:54 AM PDT

I am working on an application that registers energy-usage(water, gas, electricity) for Users. A user can have more than one homes and each home can have more usages(year1, year2, year3).

On my User detail page I have a 'tab' for each home and in this tab there is also a button for adding a new usage.

I am trying to open this 'new-use' form in a modal, via remote => true. This button adds two parameters with the request :use_year and :home_id.

In my controller use/new I am creating a new use instance '@use' and try to pass the two url parameters to the corresponding attributes via an assignment.

And this just don't work. I don't know what I am doing wrong, but I cant assign a value to an attribute of this new instance of @use. Tried to do this in the rails console and that works fine. What am I doing wrong?

usescontroller.rb

def new    myparams = use_new_params    use_year = myparams[:use_year].to_i    home_id = myparams[:home_id].to_i      @use = Use.new do |u|      u.use_year = 2016 #use_year      u.home_id = 25 # home_id    end      @home = Home.find(home_id)        respond_to do |format|          format.html          format.js       end   end        private    def use_new_params    params.require(:usage).permit(:use_year,:home_id)  end  

This is the part where the button is

View.html.erb

<%= link_to       "+ usage ",      new_use_path(:usage => {:home_id => home.id, :use_year => 2016 }),      :class => 'btn btn-primary pull-xs-right',       :remote => true %>  

And this is my Use model

Use.rb

# == Schema Information  #  # Table name: uses  #  #  id          :integer          not null, primary key  #  use_year    :integer  #  gas_1       :float  #  gas_1_sum   :float  #  gas_2       :float  #  gas_2_sum   :float  #  water_1     :float  #  water_1_sum :float  #  water_2     :float  #  water_2_sum :float  #  elec_1      :float  #  elec_1_sum  :float  #  elec_2      :float  #  elec_2_sum  :float  #  extra_info  :string  #  created_at  :datetime         not null  #  updated_at  :datetime         not null  #    class Use < ActiveRecord::Base      belongs_to :home    end  

my logfile:

Started GET "/uses/new?usage%5Bhome_id%5D=24&usage%5Buse_year%5D=2016" for 127.0.0.1 at 2016-04-23 10:52:18 +0200  Processing by UsesController#new as JS    Parameters: {"usage"=>{"home_id"=>"24", "use_year"=>"2016"}}    Person Load (0.7ms)  SELECT  "people".* FROM "people" WHERE "people"."id" = $1  ORDER BY "people"."id" ASC LIMIT 1  [["id", 1]]    Home Load (0.3ms)  SELECT  "homes".* FROM "homes" WHERE "homes"."id" = $1 LIMIT 1  [["id", 24]]    Rendered uses/_errors.html.erb (3.2ms)    Rendered uses/_useForm.html.erb (454.1ms)    Rendered uses/new.js.erb (456.2ms)  Completed 200 OK in 480ms (Views: 462.3ms | ActiveRecord: 2.1ms)  

enter image description here

This is a screenshot from my IDE. The attribute value for use_year should have a value, but is nil.

Can i read PDF header and footer and set it into new one PDF in Rails 4

Posted: 23 Apr 2016 12:52 AM PDT

I am developing Rails 4 application where need to read pdf header and footer of existing and create new with that header and footer.

Which gem is best one for it in Rails and how to do it.

Any one have idea.

Thanks

Rails, Giving a remote partial local variables

Posted: 23 Apr 2016 01:16 AM PDT

So I have this partial that has 2 variables: coursetitle and routenumber. I tried setting these variables from the view but I can't access these from the partial unless I make them global. I am looking for a way to pass on these variables from either the view or the controller but I am a bit lost as to why I can't set them from the view.

<div>  <h2> Correct!</h2>                 <%= link_to "Next", "/courses/#{coursetitle}_q#{routenumber}",class:"btn btn-warning" %>        <%= render 'layouts/coursefooter' %>            <!-- fix for bootstrap navbar render bug -->        <script>         $( ".puller" ).addClass( "pull-left" );        </script>  

I call this partial by :remote like this:

<%= link_to "Correct", correct_answer_courses_path,:remote => true,:class=>"btn btn-warning"  %>  

And my correct_answer.js looks like this:

$("#correct_answer").html("<%= j render partial: "beginnercourse/correct" %>");  

Rails map unique values and order in same statement

Posted: 23 Apr 2016 01:00 AM PDT

The following statement identifies all the unique items

@products = @volumes.map(&:product).uniq  

However, in view of further processing, the goal is to order the items as well. The following type of statement will not process because undefined method 'order' for #<Array:

@products = @volumes.map(&:product).order("max_units DESC").uniq  

How can this be accomplished succinctly?

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete