Thursday, April 14, 2016

Only show first letters of string of each word | Fixed issues

Only show first letters of string of each word | Fixed issues


Only show first letters of string of each word

Posted: 14 Apr 2016 07:21 AM PDT

I have this string

Rock Paper Shotgun  

I have looked around to find an easy way to get the first letters of each word. Because I want my end result to be:

RPS  

Is there a special ruby on rails function for this? If not, how can I achieve such thing?

I found this

str = "nishant nigam"  => "nishant nigam"  str.split(" ").map {|name| name[0].chr }.join.upcase  => "NN"  

But I was hoping if there is even a simpler method

Rspec: How to use expect to receive with a resource which does not exist yet?

Posted: 14 Apr 2016 07:07 AM PDT

In an action called via a post request I'm creating a resource call RequestOffer and send an email with ActionMailer using the created resource as a parameter:

@request_offer = RequestOffer.new(request_offer_params)  if @request_offer.save      RequestOfferMailer.email_team(@request_offer).deliver_later  end  

When my controller spec, I want to test that my RequestOfferMailer is called using the method email_team with the resource @request_offer as a parameter.

When I want to user expect(XXX).to receive(YYY).with(ZZZ), the only way I found was to declare my expectation before making the POST request. However, ZZZ is created by this POST request, so I have no way to set my expectation before.

# Set expectation first  message_delivery = instance_double(ActionMailer::MessageDelivery)    # ZZZ used in .with() does not exist yet, so it won't work  expect(RequestOfferMailer).to receive(:email_team).with(ZZZ).and_return(message_delivery)  expect(message_delivery).to receive(:deliver_later)    # Make POST request that will create ZZZ  post :create, params  

Any idea how to solve this problem?

Issue staring docker container with nginx and passenger

Posted: 14 Apr 2016 07:04 AM PDT

I am getting this weird issue in my docker container when I try to starting it. The container is trying to run a rails 4 app using nginx and passenger, but I am using the package ulyaoth-nginx-passenger5 that install nginx already build with passenger.

This configuration is working right outside the container in a VPS.

The message is: nginx: [alert] could not open the passenger log file for writing during Nginx startup, some log lines might be lost (will retry from Passenger core) (2: No such file or directory)

Any ideas how to fix it?

[vns@localhost logica-erp]$ docker run -p 80:80 -d --name logica-erp peopleware/logica-erp   e18235436c7c57081fc7520f19913a39be6026f82f23697fdd831f5b3acd563f  Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.  [vns@localhost logica-erp]$ docker ps  CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES  [vns@localhost logica-erp]$ docker start -i logica-erp   nginx: [alert] could not open the passenger log file for writing during Nginx startup, some log lines might be lost (will retry from Passenger core) (2: No such file or directory)  

You can check the docker file here: https://gist.github.com/victorsosa/7fe84b94d6f525021ac1f783adddf86b

How do I set up Devise with Angular2?

Posted: 14 Apr 2016 06:33 AM PDT

Things I want to know are:

  1. How do I check if user is signed in?
  2. How do I tell Angular to route (for example) /login, if user is not signed in.
  3. How do I create login / register form with authentication token

I'm making some researches on my own, so I will answer on this questions too. So, my goal is to make a FAQ about pairing Devise with Angular2.

Or maybe there if there is an article about that already -- I will be more than thankful.

Web server and application server Ruby on rails

Posted: 14 Apr 2016 06:43 AM PDT

Best practice for Scalable project on ruby on rails. Problem: I don't understand the difference between web and app server in ror projects.

I understood that the differences between application and web servers are webserver handles requests and application has business logic. However I don't quite understand how I can implement it in my ruby on rails application.

So, I have, for example, two instances and ruby on rails application. On the first server I want to set up a web server, and on the second one I want to install application server. But, for example, I use passengers as my webserver that makes easier to deploy my ror application. So, will I have any benefits implementing such logic? Can I use passenger as an cache server or something like this? Is it possible to put passenger on another server and send request to ror application? Or I totally wrong and don't understand the conception?

Note: I just found amazon web application hosting architecture and now I'm trying to figure out how I can it implement and how it could work.

Rails, deleting from grid works, but I get a wierd exception

Posted: 14 Apr 2016 06:20 AM PDT

I have created a grid with the wice_grid gem and I am trying to add a delete button on every entry.

My html is the following:

<%= grid(@business_grid) do |g|      g.column name: 'ID' do  |business|      business.id    end      g.column name: 'Title' do |business|      business.title    end      g.column name: 'Description' do |business|      business.description    end      g.column name: 'PlayStore URL' do |business|      business.playstore_url    end       g.column name: 'AppStore URL' do |business|     business.appstore_url   end     g.column do |business|         link_to "Delete", {:controller=>"businesses", :action=>"delete_business",:business=>business.id}       end    end -%>  

Any in my controller:

def delete_business        #debugger      @business = Business.find(params[:business])      @business.destroy          respond_to do |format|            format.html { render :partial => 'businessPartial'}            format.xml  { head :ok }            end      end  

The delete function actually works, it does indeed delete the item, but then I get an ActionController Exception saying that the object can't be found

It seems to me like I delete it and then search for it again, but I don't understand why. Here's a screenshot of what I get when I click on the Delete link. screenshot When I refresh the item is gone, which means that the delete function works.

I tried searching but I found nothing so specific. Any help appreciated.

Rails + Ec2 + multiple environment

Posted: 14 Apr 2016 06:19 AM PDT

I am ROR developer and I am getting one issue. Please read the details below about issue.

I have deployed my Rails application on Ec2 server and I am managing 3 environment (staging, testing, production) on single Ec2 instance and I am using nginx + passenger server. I am using those environment via port number. for example staging url: http://ec2ipaddress:8080/users/sign_in testing url: http://ec2ipaddress:5000/users/sign_in

now what issue I am getting suppose I am running my application(in staging environment) on any browser then after few hours it says like refused connection and it does not display anything in browser. and then if I change port number from 8080 to 5000 and hit then it works and again revert my port number 5000 to 8080 then it works fine.

I have checked the server logs and when it block then no request comes on server.

if anybody know please help me.

Regards, R.K.

Rails routing for Redmine Plugin - ActionController::RoutingError (uninitialized constant

Posted: 14 Apr 2016 06:29 AM PDT

I am new in ruby-on-rails and i am trying to develop plugin for Redmine. I have next configuration:

root:/usr/share/redmine# ruby -v  ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]  root:/usr/share/redmine# rails -v  Rails 3.2.22  

Then i created Redmine plugin in next way:

export RAILS_ENV="production"     bundle exec ruby script/rails generate redmine_plugin redmine_requirements    bundle exec ruby script/rails generate redmine_plugin_model redmine_requirements AddProject Name:string      bundle exec ruby script/rails generate redmine_plugin_controller redmine_requirements AddProject SaveProjectInformation    # ... edit routes.rb, so that:    root:/usr/share/redmine# more   plugins/redmine_requirements/config/routes.rb  # Plugin's routes  # See: http://guides.rubyonrails.org/routing.html  match "requirements" => "AddProject#SaveProjectInformation"    # ... then exec    bundle exec rake redmine:plugins:migrate  service apache2 restart  

Finally, when i try to access http://localhost/requirements, i have next error and error in the log file:

Page not found The page you were trying to access doesn't exist or has been removed.

Started GET "/requirements" for xxx.xxx.xxx.xxx at 2016-04-14 15:45:40 +0300    ActionController::RoutingError (uninitialized constant AddProjectController):  activesupport (3.2.22) lib/active_support/inflector/methods.rb:230:in `block in constantize'  activesupport (3.2.22) lib/active_support/inflector/methods.rb:229:in `each'  activesupport (3.2.22) lib/active_support/inflector/methods.rb:229:in `constantize'  actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:69:in `controller_reference'  actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:54:in `controller'  actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:32:in `call'  

Could anyone help me to fix it? Thank You in advance!

Show a selectbox with all registers that employee using or no associations

Posted: 14 Apr 2016 06:39 AM PDT

So, I have a model Refinancing belongs to employee and employee has many refinancings. This employee can have many register (but register is just a column). In view refinancing, how make for show a selectbox with all registers? I tried

<%= f.association :register %>  

but don't work. I need show all register that employee. What I do?

Ruby on Rails Devise master password

Posted: 14 Apr 2016 06:34 AM PDT

I'm trying to implement the master password feature for Devise with my User model but after following the wiki article I'm getting the following error when trying to start my rails server:

/Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:324:in `Integer': can't convert Hash into Integer (TypeError)  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:324:in `sanitize_limit'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/query_methods.rb:856:in `build_arel'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/query_methods.rb:842:in `arel'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:611:in `exec_queries'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:493:in `load'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:238:in `to_a'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/finder_methods.rb:474:in `find_nth_with_limit'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/finder_methods.rb:130:in `first'  	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/querying.rb:3:in `first'  	from /Users/godzilla/Documents/Coding/app-api/app/models/user.rb:142:in `<class:User>'  	from /Users/godzilla/Documents/Coding/app-api/app/models/user.rb:1:in `<top (required)>'

So, it indicates there is an error on line 142 in my User model. For the time being, I just cut and pasted the code straight from the wiki to get the implementation going.

models/user.rb

134  # enables a Master Password check  135  def valid_password?(password)  136    return true if valid_master_password?(password)  137    super  138  end  139  140  # WARNING: Master User password changes require an application process restart  141  DEFAULT_MASTER_USER_EMAIL = 'auser@mydomain.com' # config # SUGESTION: Move to an app configuration file  142  DEFAULT_MASTER_USER = self.first(email: DEFAULT_MASTER_USER_EMAIL) # cache  143  DEFAULT_ENCRYPTED_MASTER_PASSWORD = DEFAULT_MASTER_USER.try(:encrypted_password) # cache  144  # Code duplicated from the Devise::Models::DatabaseAuthenticatable#valid_password? method  145  # TODO: Propose Devise::Models::DatabaseAuthenticatable#valid_password?(password, encrypted_password) method and use it here  146  def valid_master_password?(password, encrypted_master_password = DEFAULT_ENCRYPTED_MASTER_PASSWORD)  147    return false if encrypted_master_password.blank?  148    bcrypt_salt = ::BCrypt::Password.new(encrypted_master_password).salt  149    bcrypt_password_hash = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt_salt)  150    Devise.secure_compare(bcrypt_password_hash, encrypted_master_password)  151 end

Is there something else that I need to do to get this working? Based on what Devise says, it should pretty much be a cookie-cutter implementation.

heroku custom domain with cname for staging app

Posted: 14 Apr 2016 06:14 AM PDT

I host my personal website on heroku with a custom domain name, pointing to my heroku app with cname.

I am doing the same thing for another app(as staging app) as staging.mywebsite.com.

The problem is that when I visit the original heroku url for my staging app it works fine, but when I visit staging.mywebsite.com "No such app" error shows up.

Any ideas? Thank you!

How to handle HTTP authentication for web app which will be accessed by other third party applications only?

Posted: 14 Apr 2016 06:09 AM PDT

I am building a rails application which has both API and UI, i have implemented HTTP token authentication(header) for API and want to continue with same for web app as well(If possible).

I am saving the user token in a session[:token] and using authenticate_or_request_with_http_token method for authentication. The application_controller has the before filter and all other controllers are inherited hence it requires HTTP header token for every endpoint in API and every page in the web app.

API is working fine because the partner application sends token every time to access endpoints but in case of web app we are getting token for the first time (when the user gets redirected from the partner app) and control gets transferred to our app. Then we need a way to send HTTP header token for every route/page inside the rails app.Please suggest me a way to do that, or a completely different approach if this seems so complex.

Rails in a subdirectory behind apache reverse proxy

Posted: 14 Apr 2016 06:20 AM PDT

I don't get it. I tried to run a Rails app behind an apache reverse proxy. I'm using Unicorn on port 8080.

bundle exec unicorn -c config/unicorn.rb -E production -p 8080  

Apache VirtualHost

ProxyPass /foo/ http://localhost:8080/  ProxyPassReverse /foo/ http://localhost:8080/  

This basically works. A request to http://domain.tld/foo/ arrives at the Rails app. What follows is a redirect to an authentication mechanism using the following in ApplicationController.before_filter:

redirect_to controller: 'sessions', action: 'index'  

As expected, I will be redirected to http://domain.tld/sessions/. Now I'd like to configure Rails to redirect to http://domain.tld/foo/sessions/ globally, without explicitly mentioning it with every redirect.

I tried using this in config/environments/production.rb:

config.relative_url_root = '/foo'  config.action_controller.relative_url_root = '/foo'  

And starting Unicorn with this:

RAILS_RELATIVE_URL_ROOT='/foo' bundle exec unicorn -c config/unicorn.rb -E production -p 8080  

Unfortunately, this does not work. It doesn't change the behaviour at all. I've added debug output before the redirect to see, what's going on.

puts Rails.application.config.relative_url_root  puts ENV['RAILS_RELATIVE_URL_ROOT']  puts url_for controller: 'sessions', action: 'index'  

This prints out:

/foo  /foo  http://domain.tld/sessions  

Can anybody tell me why Rails does not take the configuration into account?

How to display the button in one line after the input tag, which is embedded in a div block?

Posted: 14 Apr 2016 05:56 AM PDT

For nested forms I use gem coocon. I have next view

_poll_item_field.html.erb

.poll_row    .poll_item      = f.input :answer, input_html: { class: 'ctrlenter expanding' }, label: false, placeholder: 'Введите вариант ответа'      = button_tag 'Up', class: 'btn btn-bg', id: 'up_id', type: 'button'      = button_tag 'Down', type: 'button', class: 'btn btn-bg', id: 'down_id'        = link_to_remove_association "delete", f, { wrapper_class: 'poll_item' }  

Generated html

<div class="poll_item">        <div class="control-group string required blog_post_poll_poll_items_answer">          <div class="controls"><input class="string required ctrlenter expanding" display="inline" id="  blog_post_poll_attributes_poll_items_attributes_0_answer" margin="0" name="blog_post[poll_attributes][poll_items_attributes][0][answer]" placeholder="Введите вариант ответа" size="50" type="text">          </div>      </div>        <button class="btn btn-bg" display="inline" id="up_id" name="button" type="button">up</button>        <button class="btn btn-bg" display="inline" id="down_id" name="button" type="button">down</button>        <input id="blog_post_poll_attributes_poll_items_attributes_0__destroy" name="blog_post[poll_attributes][poll_items_attributes][0][_destroy]" type="hidden" value="false"><a href="#" class="remove_fields dynamic" data-wrapper-class="poll_item">delete</a>      </div>  

There is a field for input with class ctrlenter expanding, after two buttons "up" and "down" to be added . At the moment, these buttons are displayed after the input field on the next line, and it is necessary that they were in one line in place with input field. What styles I should add in order to realize this?

I added in _layout.sass

#up_id, #down_id     display: inline-block     

But dont wotk

How to prevent acts_as_votable from redirecting or refreshing? (Rails gem)

Posted: 14 Apr 2016 05:23 AM PDT

I just se the acts_as_votable and its working properly but the problem is it redirecting to the post's link and when I add

redirect_to :back  

It refreshes the page, any suggestions?

swap hash1 keys with hash2 values

Posted: 14 Apr 2016 06:20 AM PDT

What's the shortest way to swap h1 keys with h2 values:

h1 = {a: 1, b:2, c:3}  h2 = {a: 'a1', b: 'b1'}  

this is the result I want to have after the swap:

h1 = {a1: 1, b1: 2, c:3}  

NoMethodError while rendering a partial

Posted: 14 Apr 2016 05:22 AM PDT

I have a welcome.html.erb page with welcome_controller. On this page I try to render a partial which belongs to Screen model, but it returns NoMethodError: undefined method 'each' for nil:NilClass. Here's the code:

welcome.html.erb:

<%= render 'screens/all` %>  

_all.html.erb:

<%= @screens.each do |screen| %>      <%= link_to screen do %>          <img src="">      <% end %>  <% end %>  

screens_controller.rb:

def all      @screens = Screen.all.order('created_at ASC')  end  

out of stock in spree app

Posted: 14 Apr 2016 05:02 AM PDT

I am trying to work with a spree app.

I want to mark one of the variants of my product out of stock.

How can I do that in a spree app?

To the same product, in the front-end I want to show out of stock option there.

But I am not sure how can I mark that product out of stock and vice-versa.

Anyone else tried this?

Rails 4 and Mongoid nested has_one relationship not working?

Posted: 14 Apr 2016 06:21 AM PDT

I'm having a problem with a has_one relationship inside an embedded relationship. The relationship is recipe embeds_many ilist, ilist has_one ingredient. I am using a single form for this but when I submit the ingredient is not stored in the ilist.

recipe model

class Recipe   include Mongoid::Document   .   .     embeds_many :ilists      accepts_nested_attributes_for :ilists,      :allow_destroy => true,      :reject_if     => :all_blank,      autosave: true  end  

recipe controller

class RecipesController < ApplicationController    before_action :set_recipe, only: [:show, :edit, :update, :destroy]      # GET /recipes    # GET /recipes.json    def index      @recipes = Recipe.all    end      # GET /recipes/1    # GET /recipes/1.json    def show    end      # GET /recipes/new    def new       @recipe = Recipe.new       3.times { @recipe.ilists.build }    end      # GET /recipes/1/edit    def edit    end      # POST /recipes    # POST /recipes.json    def create      @recipe = Recipe.new(recipe_params)        respond_to do |format|        if @recipe.save          format.html { redirect_to @recipe, notice: 'Recipe was successfully     created.' }          format.json { render :show, status: :created, location: @recipe }        else          format.html { render :new }          format.json { render json: @recipe.errors, status: :unprocessable_entity }        end      end      end      # PATCH/PUT /recipes/1    # PATCH/PUT /recipes/1.json    def update      respond_to do |format|        if @recipe.update(recipe_params)          format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }          format.json { render :show, status: :ok, location: @recipe }        else          format.html { render :edit }          format.json { render json: @recipe.errors, status: :unprocessable_entity }        end      end      end      # DELETE /recipes/1    # DELETE /recipes/1.json    def destroy      @recipe.destroy      respond_to do |format|        format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_recipe        @recipe = Recipe.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def recipe_params        params.require(:recipe).permit(:title, :photo, :type, :preptime, :serves, :description, :calories, :protien, :Fat, :cholesterol, :sodium, :potassium, :carbohydrate, :fiber, :sugar, :calcium, :iron, :zinc, :copper, :choline, :fluoride, :folate, :magnesium, :manganese, :phosphorus, :potassium, :selenium, :vitaminA, :vitaminB1, :vitaminB2, :vitaminB3, :vitaminB4, :vitaminB5, :vitaminB6, :vitaminB12, :vitaminC, :vitaminD, :vitaminE, :vitaminK, :vegetarian, :lactovegetarian, :vegan, :halal, :pescetarian, :glutenfree, :alcohol, ilists_attributes: [ :ingrediant, :quantity])      end  end  

ilist model

class Ilist    include Mongoid::Document    field :quantity, type: Integer      has_one :ingrediant      accepts_nested_attributes_for :ingrediant,      :allow_destroy => true,      :reject_if     => :all_blank,      autosave: true    embedded_in :recipe, inverse_of: :ilists  end  **ilist controller params**  params.require(:ilist).permit( ingrediant_attribute: [ :name, :calories,..], :quantity)  

Ingrediant model(I know I spelled ingredient wrong)

class Ingrediant   include Mongoid::Document   field :name, type: String   field :calories, type: BigDecimal   field :protien, type: BigDecimal   .   .     belongs_to :ilist  end  

form:

<%= form_for @recipe, :html => { :multipart => true } do |f| %>  .  <%= f.fields_for :ilists do |builder| %>    <tr>      <td><%= builder.collection_select :ingrediant, Ingrediant.all, :id, :name, {} %></td>    <td><%= builder.text_field :quantity %></td>      </tr>  <% end %>  

In the HTTP post in the console I can see the recipe post along with

"..,ilists_attributes"=>{"0"=>{"ingrediant"=>"56ccc8b7de301b1904488361", "quantity"=>"100"},..  

56ccc8b7de301b1904488361 is the _id for chicken breast in the ingredient database, i don't want just the _id i need to be able to query the whole ingredient.

The idea is that each ilist contains all the information from an ingredient as well as the quantity so I can calculate the nutritional values of the recipe through the controller on create(not sure how to do this but one problem at a time).

Solr Sunspot - Reindexing objects is not automatically running

Posted: 14 Apr 2016 06:09 AM PDT

i'm using Sunspot Solr for indexing and searching in our Ruby on Rails application with MangoDB database (Mongo mapper)

The searching works well, but objects aren't automatically indexed to Solr when i make changes on my database.

I tried manually index on a class itself:

Top.reindex Sunspot.commit  

Or, I added on sunspot.yml : auto_commit_after_request: true I also autocommit with some interval on solrconfig.xml :

<autoCommit>  <maxDocs>10000</maxDocs>  <maxTime>15000</maxTime>  </autoCommit>  

All this solutions failed to reindex automatically my objects, unless i reindex all objects with rake task :

bundle exec rake sunspot:reindex   

Any other solutions ?

Thanks a lot.

migrating From Prototype to jQuery what will be equivalent of new Ajax.updater

Posted: 14 Apr 2016 05:00 AM PDT

The below code need to migrate from prototype to jQuery i have written the equivalent of this code but have doubt in how to handle {success: 'added_udf_filters'} in jQuery

 new Ajax.Updater({success: 'added_udf_filters'}, '/reports/add_udf_selection_row', {         parameters: {udf_key: filter_key},         method: 'get',         insertion: 'bottom',         evalScripts:  true,          onCreate: function() {          $('udfFiltersWorking').show();         },         onComplete: function() {           $('udfFiltersWorking').hide();         },         onSuccess: function(response) {           sel_obj.select('[value=' + filter_key + ']')[0].remove();           if ($('select_udf_filter').select('option').length <= 1)             $('filter_select').up('table').hide();         },         onFailure: function(response) {           alert("Error: " + response.statusText);         }       });    }   });  

The Equivalent code which i have written in jQuery is

    jQuery.ajax({        url: '/reports/add_udf_selection_row',        dataType: 'text',        success: function(data) {          jQuery("#added_udf_filters").html(data);        }      })        .done(function(data) {           sel_obj.select('[value=' + filter_key + ']')[0].remove();          if (jQuery('#select_udf_filter').select('option').length <= 1)            jQuery('#filter_select').closest('table').hide();        })          .always(function() { jQuery('#udfFiltersWorking').hide(); })          .fail(function(jqXHR, textStatus, ex) {          "use strict";          alert('Error: ' + textStatus + ' : ' + ex);        });  

Is it a good practice to use Enum for the type field in STI?

Posted: 14 Apr 2016 06:58 AM PDT

I have a requirement to list all the type values of STI. So I would like to maintain all the possible values of type.

Is it a good practice to make the type field an Enum in the parent class?

How can i get country name in Rails?

Posted: 14 Apr 2016 05:20 AM PDT

I am developing Rails 4 application where i tried lots for get user country means user open my site in which country that i want to get.

I tried

> Geocoder where too much load and not get proper output  > jQuery /Javascript code but always ask to user for share location which one is not good way  > geoip where get only ip country which always return server ip location not user browser location  

Any other way.

Thanks

"Cannot redirect to nil!"

Posted: 14 Apr 2016 06:00 AM PDT

I'm following along with Michael Hartl's rails tutorial and making small adjustments. Users can make microposts (status updates) on their profiles, at which point the page will appear to reload and their new status will be displayed. I can confirm by hand that this works exactly as intended. The problem is that tests for it aren't passing for some reason, even though the end result outside of tests looks perfect.

Screenshots of microposts_controller.rb, microposts_interface_test.rb (the failing test), related error messages, and users_controller.rb, in that order: http://imgur.com/a/IS1HI

microposts_controller.rb

class MicropostsController < ApplicationController    before_action :logged_in_user, only: [:create, :destroy]    before_action :correct_user,   only: :destroy      def create      @micropost = current_user.microposts.build(micropost_params)      if @micropost.save        flash[:success] = "Status updated!"        redirect_to @user      else        @feed_items = []        flash[:warning] = "Status was blank!"        redirect_to @user      end    end      def destroy      @micropost.destroy      flash[:success] = "Status deleted."      redirect_to @user    end  

microposts_interface_test.rb:

require 'test_helper'    class MicropostsInterfaceTest < ActionDispatch::IntegrationTest      def setup      @user = users(:mrtestit)    end      test "micropost interface" do      log_in_as(@user)      assert is_logged_in?      # Invalid submission      assert_no_difference 'Micropost.count' do        post microposts_path, micropost: { content: "" }      end      # Valid submission      content = "This status really ties the room together"      assert_difference 'Micropost.count', 1 do        post microposts_path, micropost: { content: content }      end      follow_redirect!      assert_match content, response.body      # Delete a post.      assert_select 'a', text: 'delete'      first_micropost = @user.microposts.paginate(page: 1).first      assert_difference 'Micropost.count', -1 do        delete micropost_path(first_micropost)      end      # Visit a different user.      get user_path(users(:archer))      assert_select 'a', text: 'delete', count: 0    end    end  

users_controller.rb:

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.where(activated: true).paginate(page: params[:page])    end      def show      @user = User.find(params[:id])      if logged_in?        @micropost = current_user.microposts.build        @feed_items = current_user.feed.paginate(page: params[:page])      end      @microposts = @user.microposts.paginate(page: params[:page])      redirect_to root_url and return unless @user.activated?    end  

I understand that, for some reason, this is saying that @user is nil. However, I've confirmed many times over that redirect_to @user works everywhere else.

The fact that every other test passes is already proof of that, but just to go the extra mile, I've confirmed that the failing redirect_to @user line of code works in other files, such as when a user updates their profile information under their settings page and is then redirected to their profile page. I've spent over 10 hours working on this (mostly yesterday) and am on the verge of simply deleting this test and moving on with my life. Stackoverflow is my last resort.

how to convert duedate.date to duedate.datetime in rails after migration

Posted: 14 Apr 2016 03:52 AM PDT

I have a small problem that i am facing. When i started the project i used scaffold and defined due_date field as Date now i want to do some date calculations. and i need to change the due_date field to Datetime . Can sm1 help me with this I know how to add new fields to table and delete but i am stuck at changing the attribute of already existing Model.

I have tried everything. Please let me know if there is any special code i can run in terminal to edit the attribute and create migration file.

P.s- Someone told me changing the schema file is bad. so i cant edit it directly.

Starting one delayed job in Rails creates two processes

Posted: 14 Apr 2016 06:02 AM PDT

Initially I have no process for delayed jobs(as indicated by htop), then when I run the command RAILS_ENV=production bin/delayed_job start I got one delayed job worker, as indicated by files in tmp/pids. However htop indicates now that there are two processes, as shown in the picture below. enter image description here

So why is this happening? The other delayed job consumes memory where I don't have much of it!, however its TIME+ is zero, so it didn't consume time, so what does this means ?

Rails routing: Scope using a database field

Posted: 14 Apr 2016 05:38 AM PDT

I am creating an multitenant app based on ideas from Ryan Bigg's book "Multitenancy with Rails". In this book, the tenants has their own subdomain. This approach is not applicable in my case, so I'm trying to scope by a slug of the account's name instead.

So instead of URLs like http://account-name.myapp.com, i want http://myapp.mydomain.com/account-name/. The subdomain is reserved for the app itself, because I want to be able to have more than one app on my domain.

Here's a piece of my routes.rb:

scope module: 'accounts' do    resources :customers do      resources :notes    end  end  

To achieve my goal, i try to follow the routing guide on rubyonrails.com (the last code snippet in chapter 4.5), and change the above code to:

scope ':slug', module: 'accounts' do    resources :customers do      resources :notes    end  end  

slug is an attribute in the accounts table in the database, so if an account is called "My Business", the slug will typically be "my-business".

This change seems to correct my routes:

customers GET    /:slug/customers(.:format)    

.. but it also seems to break my site, as the slug is not fetched from the database. I can't seem to wrap my mind around how this scope':slug', module: 'accounts' works. Is Rails supposed to automatically recognize :slug as an attribute of the Accoounts table? If not, can anyone please help me find a way to use the account's slug in my URLs?

I have googled around for a couple of days now, and read numerous answers here on Stackoverflow. Nothing helped, so any pointers is greatly appreciated. :-)

how to redirect to dashboard when visit certain page using ActiveAdmin

Posted: 14 Apr 2016 03:30 AM PDT

i`m using ActiveAdmin gem in my Rails Application,

i added some role to give user privileges, a basic admin can not access certain menu.

I have remove the menu by using this code if type admin is basic admin

menu false  

The problem is, the basic admin still can access that menu even though i have removed it via URL typed.

Are there any solutions to restrict the basic admin to access that page?

My idea is to not Register that page at all if admin type is basic admin

Rails, ActiveRecord and SubQueries

Posted: 14 Apr 2016 07:05 AM PDT

I have a postgresql database with hourly gas consumption entries. Now, I need to find the days with the highest consumption for every month.

In plain SQL I'd use subqueries like this:

SELECT       DATE_TRUNC('month', day) AS month,      MAX(dailyconsumption) as maxconsumption  FROM (      SELECT           DATE_TRUNC('day', date) AS day,          SUM(consumption) AS dailyconsumption      FROM Records      GROUP BY day  ) t  GROUP BY month  

However, I don't know the best way (or any way) to do this in rails. I appreciate any input. Should I bypass ActiveRecord? Performance is a high priority.

Thank You!

Updating a local gem with c extensions

Posted: 14 Apr 2016 03:13 AM PDT

I've cloned a gem from github and using it locally by providing local path in Gemfile.

gem 'abc' , path: 'path/to/abc'  

The gem has c extension that I want to make some changes to. I made changes in a file located at ext/my_file.c and ran the bundle install command. The changes are not reflecting. What else should I do to reflect the changes?

Your help is appreciated.

No comments:

Post a Comment