Saturday, November 26, 2016

Rails coffe render template | Fixed issues

Rails coffe render template | Fixed issues


Rails coffe render template

Posted: 26 Nov 2016 06:56 AM PST

I have lists in erb and form, when I add new list I want see new element without reload page

lists page

<p id='lists'>   <%= render 'lists/lists', object: @user %>  </p>  

I have lists and when I add new list want reload tag by id, in js coffe find class and render for my partial, but have error

ActionView::Template::Error (SyntaxError: [stdin]:5:28: unexpected string):  1:   2: $("#lists").prepend("<%= (render partial: "lists/lists")%>");  3: $('form')[0].reset()  

Try another way

$("#lists").prepend("<%= escape_javascript(render partial: "lists/lists")%>");  

have last list, but all list double in page

how to correct render partial for some id in coffee ?

Polymorphic relation "undefined method `comments' for #<Post..." error

Posted: 26 Nov 2016 06:33 AM PST

I tried to create a simple posts-comments relation. Here is my model: Here is my Comment model:

class Comment < ActiveRecord::Base      belongs_to :commentable, polymorphic: true      belongs_to :user  end  

Here is my Post model:

class Post < ActiveRecord::Base      belongs_to :user        has_many :comments, as: :commentable  end  

And here is the schema that got generated:

  create_table "comments", force: :cascade do |t|      t.text     "body"      t.integer  "commentable_id"      t.string   "commentable_type"      t.datetime "created_at"      t.datetime "updated_at"    end      add_index "comments", ["commentable_type", "commentable_id"], name: "index_comments_on_commentable_type_and_commentable_id", using: :btree  

All seems good and well. But when I do in the console:

 Post.last().comments()  

I get an error:

NoMethodError: undefined method `comments' for #<Post:0x0000000357e2b8>      Did you mean?  committed!              from /usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/attribute_methods.rb:433:in `method_missing'              from (irb):36  

I am completely stuck! This surely has to be some kind of a silly typo.

Active model serializer, render association without key

Posted: 26 Nov 2016 06:20 AM PST

I have a table named featured_products witch contains only two columns (product_id, position). On my GET /featured_products, I want to render something like this

[     { "name":"Product 1" }     { "name":"product 2" }  ]  

But instead, I logically get this:

[     "product":{ "name":"Product 1" }     "product":{ "name":"product 2" }  ]  

Following the doc of Active Model Serializers, I'v tried these in my featured_product serializer class:

embed_in_root: true  

and

belongs_to :product, embed_in_root: true  

but the first on gives an error while second changes the JSON in no way.

I don't know if I missed the answer I'm looking for in Active Model Serializer's doc or if the answer is to be found elsewhere, but I didn't manage to solve this on my own, I'd be happy to get some advices here.

Thanks

carrierwave default image update without file select & upload

Posted: 26 Nov 2016 06:02 AM PST

Many users have asked same question but I am stacked..

Rails : 4.2.5

Carrierwave

Cloudinary

I want to upload an avatar image as default when a user is created.

class UsersController < ApplicationController      after_action :set_default_avatar!, only: [:create]        def create         **************         **************      end        def set_default_avatar!         url = ImageUploader.default_url()         @user.update_attribute(:avatar, url)      end  end    class ImageUploader < CarrierWave::Uploader::Base        def self.default_url()          ActionController::Base.helpers.asset_path("fallback/" + "avatar_#{rand(1..15).to_s}.jpg"])      end    end  

once a user creation process is completed, then "after_action" is processed.

"default_url" returns a random image path which is located in 'public/fallbak/'.

I put the url in user.avatar, the users avatar has been updated as NULL. Neither no image was uploaded on Cloudinary.

Basically, I want to store images at Cloudinary service.

When a user edit users information at a screen, they could be able to upload avatar image.

However I cant upload an image as default avatar by the logic above.

I red the document of Carrierwave, but it doesn't work for me.

I believe that something is missing in my code.

Any help is very appreciated.

Gem 'better_errors' not working Rails 5.0.0

Posted: 26 Nov 2016 07:32 AM PST

I installed gem better_errors version 2.1.1 for my ruby on rails application. However, I still get the same old debug page. I have also installed the gem binding_of_caller. I even installed the three gems which as shown as runtime dependencies for better_errors, namely erubis, coderay and rack(see the gem page here). All this to no avail.

I have also tried other solutions, one is this. All this to no avail.

I am using Ubuntu 16.04, rails 5.0.0.1 and ruby 2.3.1p112.

Rails association using OR

Posted: 26 Nov 2016 05:55 AM PST

Given a List model with the following associations:

has_many :list_group_memberships, dependent: :destroy  has_many :groups, through: :list_group_memberships  has_many :users, -> { unscope(:order).uniq }, through: :groups, source: :users  

Basically I need to return the following but as an ActiveRecord::Relation, not an array:

def users    super + [user]  end  

Ideally, the users relation would use an or scope, but I can't work it out.

Let divs inside overflow parent

Posted: 26 Nov 2016 05:43 AM PST

I have a div, where there are listed all user "items".

If user hovers over some item it shows a "hint cloud" with a name of an item.

I have a problem, because I'm using a CustomScrollbar Ruby gem, in items next to border of the game, the "hint clouds" with names of the item are cut.

What should I do to let it overflow parent?

I am trying to install sublime in my ubuntu 16.04 machine but getting these error

Posted: 26 Nov 2016 05:29 AM PST

If anyone know how to solve this problem please comment. I am getting frustrated for this.

You might want to run 'apt-get -f install' to correct these:  The following packages have unmet dependencies:   chromium-browser-l10n : Depends: chromium-browser (>= 51.0.2704.79-0ubuntu0.16.04.1.1242) but 50.0.2661.102-0ubuntu0.16.04.1.1237 is to be installed   libgomp1 : Depends: gcc-5-base (= 5.4.0-6ubuntu1~16.04.2) but 5.3.1-14ubuntu2 is to be installed   libtsan0 : Depends: gcc-5-base (= 5.4.0-6ubuntu1~16.04.2) but 5.3.1-14ubuntu2 is to be installed   libubsan0 : Depends: gcc-5-base (= 5.4.0-6ubuntu1~16.04.2) but 5.3.1-14ubuntu2 is to be installed   sublime-text : Conflicts: sublime-text-installer but 3126-2~webupd8~1 is to be installed   sublime-text-installer : Conflicts: sublime-text  W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target Packages (main/binary-i386/Packages) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target Translations (main/i18n/Translation-en_IN) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target DEP-11 (main/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  W: Target DEP-11-icons (main/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list.d/pgdg.list:1 and /etc/apt/sources.list.d/pgdg.list:2  E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).  

Outputting multiple variables in Rails after parsing XML

Posted: 26 Nov 2016 05:20 AM PST

I have managed to parse an XML document and can output the variable I want as shown below:

require('Nokogiri')  require 'property.rb' #Require the Property class in models folder    class PropertiesController < ApplicationController      def index      #Load XML file into a String      xml_file = File.read("#{Rails.root}/public/property.xml")        #Parse the XML file with Nokogiri      properties = Nokogiri::XML.parse(xml_file)        #Extract the results of each property in XML file      properties.root.elements.each do |node|        if node.node_name.eql? 'property'          parse_property(node)        end      end    end      #Parse each property and extract details    def parse_property(node)      @new_property = Property.new      @new_property.department = node.at('department')      @new_property.price_text = node.attr("price_text")      @new_property.price = node.attr("numeric_price")      @new_property.beds = node.attr("bedrooms")      @new_property.receptions = node.attr("receptions")      @new_property.bathrooms = node.attr("bathrooms")      @new_property.header = node.attr("advert_heading")      @new_property.main_ad = node.attr("main_advert")      @new_property.house_name = node.attr("house_number")      @new_property.street = node.attr("street")      @new_property.town = node.attr("town")      @new_property.county = node.attr("county")      @new_property.postcode = node.attr("postcode")    end    end  

And HTMl.erb (example)

<% @new_property.department %>  

However, when I am going to be parsing the proper XML document I will have more than one property detail to output, but I can't find how I go about this. I have tried:

<% @new_property.each do |property| %>  

and then listing the details but I get an error that new_property is a nil class.

Many thanks Sion

Rails association doesn't work

Posted: 26 Nov 2016 05:31 AM PST

I am having a weird issue that I can't figure out.

It is very basic rails programming : I want to create an association between a user model and a goal model.

goal.rb

class Goal < ActiveRecord::Base      belongs_to :user  end  

user.rb

class User < ActiveRecord::Base    has_many :goals, dependent: :destroy    has_many :records    has_many :orders  end  

When I am making the association from the console, it is working well, lets say :

$ goal = Goal.first  $ goal.user_id = 1  $ goal.save   $ goal.inspect       #<Goal id: 1, description: "loremipsum", created_at: "2016-11-26 12:39:34", updated_at: "2016-11-26 12:43:41", name: "ipsumlorem", user_id: 1>   

But then, when I am creating a goal from my views, the association is not made, and the user_id of the goal user_id remain : nil.

Any ideas ?

EDIT AS REQUIRED :

_form.html.erb

<%= form_for(@goal) do |f| %>    <%= f.text_field :name, class: "form-control" %>    <%= f.text_area :description, class: "form-control"  %>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

goal_controller.rb

  def new      @users = User.all      @goal = current_user.goals.build    end      def edit    end      def create      @goal = Goal.new(goal_params)      @goal.save      redirect_to root_path, notice: "Objectif sauvegardé"      end  

Change default port number of unicorn using config/unicorn/unicorn.rb configs

Posted: 26 Nov 2016 05:30 AM PST

How can i change unicorn's default port number using config/unicorn/unicorn.rb file configuration parameters. I need to run two unicorns with nginx on same machine how can i achieve this? Right now i am getting port address already occupied error.

app_dir = "/home/rails/apps/app_name/current"  shared_dir = "/home/rails/apps/app_name/shared"    env = "staging"    # Set unicorn options  worker_processes 1  preload_app true  timeout 30    # Fill path to your app  working_directory app_dir    # Set up socket location  listen "#{shared_dir}/sockets/unicorn.admin.sock", :backlog => 64    # Loging  stderr_path "#{shared_dir}/log/unicorn.stderr.log"  stdout_path "#{shared_dir}/log/unicorn.stdout.log"    # Set master PID location  pid "#{shared_dir}/pids/unicorn.admin.pid"    before_fork do |server, worker|    # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)    defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!    old_pid = "#{server.config[:pid]}.oldbin"    if File.exists?(old_pid) && server.pid != old_pid      begin        sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU        Process.kill(sig, File.read(old_pid).to_i)      rescue Errno::ENOENT, Errno::ESRCH        # someone else did our job for us      end    end  end    after_fork do |server, worker|    defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection  end    before_exec do |server|    ENV['BUNDLE_GEMFILE'] = "#{app_dir}/Gemfile"  end  

I am getting this error:

/shared/sockets/unicorn.admin.sock (Errno::EADDRINUSE)  

Trying to save different model before creation?

Posted: 26 Nov 2016 03:40 AM PST

I am trying to add a user role according to Rolify gem in my devise User model.

What I basically want to achieve is that, if the user has selected that he is a student or a teacher in the registration page itself, after the creation of the user, it should add the required roles to the user.

Please note that I am not storing the 'role' in the User table. I am just using attr_accessor to send me an initial value to compare.

This is my User model code :

# == Schema Information  #  # Table name: users  #  #  id                     :integer          not null, primary key  #  email                  :string(255)      default(""), not null  #  encrypted_password     :string(255)      default(""), not null  #  reset_password_token   :string(255)  #  reset_password_sent_at :datetime  #  remember_created_at    :datetime  #  sign_in_count          :integer          default(0), not null  #  current_sign_in_at     :datetime  #  last_sign_in_at        :datetime  #  current_sign_in_ip     :string(255)  #  last_sign_in_ip        :string(255)  #  created_at             :datetime         not null  #  updated_at             :datetime         not null  #  avatar                 :string(255)  #  username               :string(255)  #    class User < ActiveRecord::Base    # This is for the user roles.    rolify    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      attr_accessor :role    # Adding the carrierwave uploader    mount_uploader :avatar, AvatarUploader        before_create :add_specified_role      def add_specified_role      if self.role == 0        # I am sure I am messing it up here and this is not the way.. :/        after_create :add_student_role      elsif self.role == 1        after_create :add_teacher_role      end    end        def add_student_role      self.add_role(:student) if self.roles.blank?    end        def add_teacher_role      self.add_role(:teacher) if self.roles.blank?    end      end  

However, it does not seem to be working as when I check the roles, the role has not been added and I am sure I am doing something wrong.

What is the correct way to achieve the above task?

Rails searchkick dropdown not showing expected

Posted: 26 Nov 2016 02:36 AM PST

On my rails app, I have used searchkick for search & auto dropdown population, all are working properly but showing only five items, on my console showing 20 items which I declared on my controller limit: 20 but showing only 5 items visually.

model:

class DegreeName     searchkick match: :word_start, searchable: [:name]  end  

controller

def drop_name      render json: DegreeName.search(params[:q], {          fields: ["name"],          limit: 20,      }).map(&:name)  end  

view

<%= text_field_tag :name, params[:q], id: "drop" %>  

coffee script

$ ->  $('#drop').typeahead  displayKey: 'name'  remote: "/degree/drop_name?q=%QUERY"  

how to show 20 items on dropdown?

Console

enter image description here

Adding a custom field to devise invitable invitation BEFORE sending the invite

Posted: 26 Nov 2016 01:05 AM PST

So I have spent some time now trying to track down the illusive way to add a custom field to the field the "invitee" sends the invitation to.. My app is not a public facing app, and so the human resources department will send the invite upon hiring. However i would like to add basic information about the user being invited, and then they can fill out the non-pertinent info once they sign into the application..

is there a way to do this using a params sanitizer? i have only been able to find

devise_parameter_sanitizer.permit(:accept_invitation, keys: [:fname, :lname, :mobiletel, :password, :password_confirmation, :invitation_token])  

but I need to do this before the invite is sent out.

Any help would be greatly appreciated here!

Redirect with inactivity

Posted: 26 Nov 2016 01:41 AM PST

My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.

I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.

So far I'm able to set a time after which the user will be redirected to root path with the following script:

var delayedRedirect = function (){    window.location = "/";  }    var delay = 10000;    $(document).ready(function() {    setTimeout('delayedRedirect()', delay);  });  

I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.

$('#btn-persist').click(function() {    delay = 3000;    // or calling again setTimeout('delayedRedirect()', delay);  });  

But I noticed that changing the variable won't affect the setTimeout function that has already been called.

I've also tried to use the clearTimeout function as below without success

var delayedRedirect = function (){    window.location = "/persists";  }    var delay = 3000;    var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);   }    var stopRedirect = function (){    clearTimeout(triggerRedirect);  }    $(document).ready(function() {    triggerRedirect();      $('#btn-persist').click(function() {      stopRedirect();    });  });  

I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.

At the same time, I don't want to stop any other JS functions that are running in parallel.

Do you see a better solution to achieve this?

Devise common login page for login and register

Posted: 26 Nov 2016 12:59 AM PST

I'm trying to have a login and register form on one page with devise. But how can I redirect back to the common page when there is an unsuccessful try to login or register? It i being redirected to the appropriate login or register specific page.

Thanks

rails error, wrong number of arguments 2 for 1?

Posted: 26 Nov 2016 01:02 AM PST

I am following along on the railstutorial by Michael Hartl. I skipped a chapter out as was advised if desired, I am getting the same error on the User model in the rails test for both the AccountsActivationsController and PasswordResetsController, wrong number of arguements (2 for 1).

Ive spent a bit of time on this trying to see where I went wrong but thought I would ask a outsiders point of view. I am getting the error, on the same action in the user model def authenticated? from valid_user and edit actions in their respective controllers.

What may be the problem?

AccountsActivationsController

class AccountsActivationsController        def edit        user = User.find_by(email: params[:email])        if user && !user.activated? && user.authenticated?(:activation, params[:id])          user.activate          user.update_attribute(:activated,    true)          user.update_attribute(:activated_at, Time.zone.now)          log_in user          flash[:success] = "Account activated!"          redirect_to user        else          flash[:danger] = "Invalid activation link"          redirect_to root_url        end      end  end  

PasswordResetsController

class PasswordResetsConrtoller     .     .     .        def valid_user        unless (@user && @user.activated? &&                @user.authenticated?(:reset, params[:id]))        redirect_to root_url      end    end     .     .  

User model

class User     .     .     .        def authenticated?(activation_token)        return false if activation_digest.nil?        BCrypt::Password.new(activation_digest).is_password?(activation_token)      end     .     .  

Como traer la información de la tablas hijas a tablas padres en rails

Posted: 26 Nov 2016 12:24 AM PST

Data is not going into database and that's the reason it is not routing to id of that enterd data in ruby on rails?

Posted: 26 Nov 2016 01:09 AM PST

Controller code:

class ItemsController < ApplicationController        def show       end        def new       end        def create          @item = Item.new(item_params)            @item.save          redirect_to @item      end        private    def item_params      params.require(:item).permit(:mobile, :company)    end    end  

New.html.erb code

<%= form_for :item , url: items_path do |f| %>    <p>      <%= f.label :mobile %><br>      <%= f.text_field :mobile %>    </p>      <p>      <%= f.label :company %><br>      <%= f.text_field :company %>    </p>      <p>      <%= f.submit %>    </p>  <% end %>  

One more thing i don't think i am using right parameters in the private method for require. If it is so then let me know what i should use?

Prevent spam bots from hitting Rails app

Posted: 26 Nov 2016 01:25 AM PST

I have a Rails 5 app in production hosted on Heroku. I recently noticed a particularly high load on the servers and on further investigation it looks as though it's all from a group of spam bots.

These bots were hitting an 'email to friend' form that I had on the show page and available to logged-out users. I've since made the form available only to logged-in and authenticated users. I also deleted the specific record that the bots were targeting in the db, yet this hasn't done anything to stop the bots from hitting the route. (They only seem to be targeting a specific record...)

I then installed the rack-attack gem to try and throttle requests to this specific route (as well as the sign_up path), but the problem I have is that these spam requests originate from a different ip address every single time and the rack-attack gem only throttles requests from a single ip.

Can anyone provide any assistance on how to prevent these bots from hitting my site?

Here is the print out from the Heroku logs:

2016-11-26T08:01:22.784341+00:00 heroku[router]: at=info method=POST path="/jobs/389-commercial-vehicle-technician-northside-truck-van-york-mercedes-benz-uk-ltd/email_to_friend" host=www.example.com request_id=02689424-de9c-4a25-96c8-8f510a587836 fwd="203.160.52.159" dyno=web.1 connect=1ms service=11ms status=404 bytes=1812  2016-11-26T08:01:22.757585+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] Started POST "/jobs/389-commercial-vehicle-technician-northside-truck-van-york-mercedes-benz-uk-ltd/email_to_friend" for 203.160.52.159 at 2016-11-26 08:01:22 +0000  2016-11-26T08:01:22.759320+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836]     2016-11-26T08:01:22.759371+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] ActionController::RoutingError (No route matches [POST] "/jobs/389-commercial-vehicle-technician-northside-truck-van-york-mercedes-benz-uk-ltd/email_to_friend"):  2016-11-26T08:01:22.759421+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836]     2016-11-26T08:01:22.759493+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'  2016-11-26T08:01:22.759535+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'  2016-11-26T08:01:22.759575+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:36:in `call_app'  2016-11-26T08:01:22.759639+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `block in call'  2016-11-26T08:01:22.759726+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/tagged_logging.rb:26:in `tagged'  2016-11-26T08:01:22.759685+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/tagged_logging.rb:70:in `block in tagged'  2016-11-26T08:01:22.759766+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/tagged_logging.rb:70:in `tagged'  2016-11-26T08:01:22.759905+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `call'  2016-11-26T08:01:22.759944+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/request_id.rb:24:in `call'  2016-11-26T08:01:22.760009+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:22:in `call'  2016-11-26T08:01:22.760265+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/runtime.rb:22:in `call'  2016-11-26T08:01:22.760333+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  2016-11-26T08:01:22.760365+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/executor.rb:12:in `call'  2016-11-26T08:01:22.760394+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/static.rb:136:in `call'  2016-11-26T08:01:22.760422+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/bundler/gems/heroku-deflater-60d92ba0f8ae/lib/heroku-deflater/skip_binary.rb:19:in `call'  2016-11-26T08:01:22.760478+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/deflater.rb:35:in `call'  2016-11-26T08:01:22.760522+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/bundler/gems/heroku-deflater-60d92ba0f8ae/lib/heroku-deflater/serve_zipped_assets.rb:50:in `call'  2016-11-26T08:01:22.760552+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/sendfile.rb:111:in `call'  2016-11-26T08:01:22.760581+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/ssl.rb:83:in `call'  2016-11-26T08:01:22.760610+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:522:in `call'  2016-11-26T08:01:22.760650+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/configuration.rb:225:in `call'  2016-11-26T08:01:22.760699+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/server.rb:578:in `handle_request'  2016-11-26T08:01:22.760741+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/server.rb:415:in `process_client'  2016-11-26T08:01:22.760782+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/server.rb:275:in `block in run'  2016-11-26T08:01:22.760849+00:00 app[web.1]: [02689424-de9c-4a25-96c8-8f510a587836] vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/thread_pool.rb:116:in `block in spawn_thread'  

Performance optimization: Active Model Serializer

Posted: 26 Nov 2016 12:10 AM PST

I would like to improve performance of rendered json generated by ActiveModel::Serializer. Please find below sample code:

In controller,

render json: Abc.where(" flag = ?",true).order('created_at DESC').map{|p| XyzSerializer.new(p)}.to_json, :callback => params['callback']    

In AbcSerializer,

class AbcSerializer < ActiveModel::Serializer       attributes :attr1, :attr2, :attr3    def attr1   store = PQR.find_by(id: object.id)   store.name  end  def attr2   store = PQR.find_by(id: object.id)   store.pqr_association_tables.name  end  def attr3    object.image.url  end  

In XyzSerializer,

class XyzSerializer < ActiveModel::Serializer    attributes :attr1, :attr2, :attr3    def attr1   store = DEF.find_by(id: object.id)   store.name  end  def attr2   store = DEF.find_by(id: object.id)   store.created_at  end  def attr3    store = DEF.find_by(id: object.id)    store.updated_at  end  

In ABC model,

class Abc < ActiveRecord::Base    has_many   :xyzs, dependent: :destroy  end  

In Xyz model,

class Xyz < ActiveRecord::Base    belongs_to   :abc  end  

I am getting expected output. But, it takes too long. For example, it is taking more than 15 seconds to fetch 1500 records.

I have tried JBuilder gem too. But which doesn't make any difference in terms of performance.

Queris on Model DEF is executing thrice for each object, on Model PQR twice for each object, may be the bottleneck.

I am using Ruby 2.3.0 & Rails 4.2.0 with active_model_serializers (0.10.2)

Any pointers would be a great help.

Reusing Private Methods in Rails 5

Posted: 25 Nov 2016 11:50 PM PST

Most of the searched questions so far relates to "what's the difference". I need to know how to reuse each across different controllers.

Below is just an example.

ApplicationController:

private   def redirect    redirect_to welcome_path   end  

Any Controller:

class AnyController < ApplicationController   before_action :redirect, only: :about     def about   end  end  

I now have many controllers that uses the same private methods and wanted to a central place to store it. You know, keeping it DRY sort of thing. Where to place these private methods to reuse across any controller that inherits from ApplicationController? If a question like this has already been answered, please point me there. Thanks.

How does Ruby syntax for inputting arguments work?

Posted: 26 Nov 2016 12:49 AM PST

<%= f.label :password %>  <%= f.password_field :password, class: 'form-control' %>  

The method signature of password_field is:

      def password_field(object_name, method, options = {})  
  1. In the "... f.password_field :password..." line, are two arguments getting passed into password_field? So it's the same as "f.password_field(:password, class: 'form-control')?
  2. According to the method signature of pw_field, ":password" should be an object. However, it's a symbol which as I understand is more like a string than a pointer. How does inputting this as an object make sense?
  3. Why is the "class: 'form-control'" argument a method? It doesn't seem like a method to me, but it's not a hash so I assume it should not be the "options" in the method signature...

rails has many relation through other table

Posted: 26 Nov 2016 05:02 AM PST

I have 4 tables, All of them are connected to each other.

restaurant -> has_many -> menus  menu -> has_many -> categories  category -> has_many -> menu items  

I tried to access categories from restaurant through menu table and it is not working

I want to access categories and menu items from restaurant table, is it possible

for example

Restaurant.find(1).categories  Restaurant.find(1).menu_items  

how to implement bootstrap themes in rails?

Posted: 26 Nov 2016 02:18 AM PST

I'm trying to use startbootstrap themes to my rails application

http://startbootstrap.com/template-overviews/creative/

I have download the themes extract it

move the css folder into vendor/stylesheets

move the javascript folder into vendor/javascripts

edit the index.html file and remove all the dependencies from there(remove the css and remove the javascript)

then

I edit my application.js and application.css to include the css and js files from the themes

application.js  //= require vendor/jquery/jquery.min.js  //= require vendor/bootstrap/js/bootstrap.min.js  //= require vendor/scrollreveal/scrollreveal.min.js  //= require vendor/magnific-popup/jquery.magnific-popup.min.js  //= require js/creative.min.js    application.css  *= require vendor/bootstrap/css/bootstrap.min.css  *= require vendor/font-awesome/css/font-awesome.min.css  *= require vendor/magnific-popup/magnific-popup.css  *= require css/creative.min.css  

the css and image is working properly but the javascripts never work Idk why

so far my workaround is copy all the files into public folder

I need restart server on production if I want direct in sever change one line code?

Posted: 26 Nov 2016 12:14 AM PST

I have running project ruby on rails on production server(digitalocean). I need only add

User-agent: *  Disallow: /   

i dont want push to repository and update on server. I want direct change on server robot.txt. Question: I need after restart server? If yes, wich command need run to changes to take effect?

I am opening a port on a fresh Centos 7 server, but nmap says it's still closed

Posted: 25 Nov 2016 11:23 PM PST

I have installed a fresh Centos 7 box on virtualbox running in a bridged network adapter. I have installed ruby on rails and setup a simple app. I started the server on port 3000, but when I try to reach it from my host machine hitting the IP I get no response.

On the server I can do a

wget "http://127.0.0.1:3000"   

and I get the right index.html file. So I figured my port was getting blocked.

So I installed firewalld and issued the following commands

sudo firewall-cmd --zone=public --add-port=3000/tcp --permanent  sudo firewall-cmd --reload  firewall-cmd --list-all  

The list all shows the following ;

public (default, active)  interfaces: enp0s3  sources:  services: dhcpv6-client ssh  ports: 3000/tcp 80/tcp  masquerade: no  forward-ports:  icmp-blocks:  rich rules:  

However when I run nmap I see it's closed

sudo nmap -p 3000 127.0.0.1  Starting Nmap 6.40 ( http://nmap.org ) at 2016-11-26 01:47 EST  Nmap scan report for localhost (127.0.0.1)  Host is up (0.000071s latency).  PORT     STATE  SERVICE  3000/tcp closed ppp    Nmap done: 1 IP address (1 host up) scanned in 0.06 seconds  

From my host machine I can ping the machine but when I nmap to port 3000 it says the host is unreachable.

I don't know how to go any further. Any thoughts?

Get Request is passed instead of post request from new.html

Posted: 25 Nov 2016 10:40 PM PST

I am trying out for basic login and registration in ruby on rails, ISSUE: When I click register button from new.html I am getting GET request but I can see method="post" in page source of that html I have posted my code below new.html.erb

    <form>  <%= form_for(@user) do |f| %>  <%= f.label :user_name %>  <%= f.text_field :user_name %></br>  <%= f.label :email_id %>  <%= f.text_field :email_id %></br>  <%= f.label :password %>  <%= f.password_field :password %></br>  <%= f.label :college %>  <%= f.text_field :college %></br>  <%= f.label :major %>  <%= f.text_field :major %></br>  <%= f.label :current_job %>  <%= f.text_field :current_job %></br>  <%= f.submit("Create Account",class: "btn btn-primary") %>  <% end %>  </form>  

My index.html.erb code which is loaded while application starts

<div class="container">  <div class="row">    <div class="login">    <%= form_tag("/user/login",:method => :post) do %>  <%= label_tag(:EmailId) %>  <%= text_field_tag(:email, params[:email]) %></br>  <%= label_tag(:password) %>  <%= password_field_tag(:password, params[:password]) %></br>  <%= submit_tag("Log In",class: "btn btn-primary") %>  <%= submit_tag("Register",class: "btn btn-primary") %>    <% end %>  </div>      </div>  </div>  

My controller code

class UsersController < ApplicationController    def index      @user = User.all    end          def login      print "In Sign in controller"      @user = User.new      if params[:commit] == 'Register'        print "inside Register class"        redirect_to '/users/new'      else      @user = User.find(params[:email_id])      if @user and user.authenticate(params[:password])          sessions[:userId] = @user.user_id      end      end      end          def new      puts "****Inside New Method******"      @user = User.new    end      def create     puts "****Inside create Method******"    end   private    def user_params   end    end  

My Route code

Rails.application.routes.draw do    root 'users#index'     resources :users     post '/users/login' => 'users#login'  

As per my understanding post request should hit create method, but get /users method is hitting. Please help me out regarding this

How do named paths work in Ruby on Rails?

Posted: 25 Nov 2016 11:21 PM PST

1 2

The highlighted code in the above picture creates the named routes in the below. However, I don't understand how this setup is helpful, because if the "login_path" which is a named path variable is automatically (hidden to the user) created by "get /login" in the routes.rb file, then how do we change "login_path" to point to something else like "get /login_new_url"? I thought the whole point of the named path variables was easy posterior editing of URLs.

Capybara: How to hit the first button in rspec?

Posted: 26 Nov 2016 01:21 AM PST

Here is the html source code for 2 Save buttons in Rails 4 spec. The program should click the first Save:

<div class="btn-toolbar"> <a class="btn btn-primary" href="/view_handler?index=0"> <span class="translation_missing" title="translation missing: en.Back">Back</span> </a> <input class="btn btn-default btn btn-primary" name="commit" value="Save" type="submit"> <input class="btn btn-default btn btn-primary" name="commit" value="Save & New" and_new="true" type="submit"> </div>

Here is the code I tried:

first('input.btn.btn-default').click_button 'Save'  

The error returned is:

Capybara::ElementNotFound:         Unable to find button "Save"  

What's the right way to click button 'Save' in spec?

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