Thursday, May 12, 2016

Editor for images rmagick | Fixed issues

Editor for images rmagick | Fixed issues


Editor for images rmagick

Posted: 12 May 2016 06:54 AM PDT

I need an easy method for defining how the logos are placed on images of products. How can I implement this using RMagick or any other image library for Ruby?

How to get S3 object url using S3.client

Posted: 12 May 2016 06:54 AM PDT

I have uploaded a file in S3 in rails and i want the download url for that file but i am getting error

undefined method `url_for' for

s3 = Aws::S3::Client.new(               credentials: Aws::Credentials.new(AWS_S3_CONFIG['AWS_ACCESS_KEY_ID'],                                                 AWS_S3_CONFIG['AWS_SECRET_ACCESS_KEY']),               region: AWS_S3_CONFIG['AWS_REGION'],           )  object  = s3.get_object({bucket:'mybucket', key:'myfilename'})  url = object.url_for(:get, { expires: 10.minutes,                               response_content_disposition: 'attachment;'                              }).to_s  

How pass params to url for show in other view

Posted: 12 May 2016 06:29 AM PDT

I'm on index.html.erb where I have a search by register, when I click on button, pass by url this:

/solicite?utf8=✓&search_employee_register=201304009521&commit=Search  

And method search_employee_register is this:

 scope :search_employee_register, -> (register) { joins(:employee).where("employees.register LIKE ?", "%#{register}%") }  

My portabilities_controller is this:

  def solicite      if params[:search_employee_register]        @employee = Employee.find(register: params[:search_employee_register]).includes(:authorizations)        @authorizations = Authorization.where(employee_id: @employee)      else        @authorizations = Authorization.all      end    end   

But I have this error:

Couldn't find Employee with 'id'={:register=>"201304009521"}  

Being that I have this register, what is my wrong? I want just that show all authorizations that employee.

What is ActiveRecord Persistence?

Posted: 12 May 2016 06:26 AM PDT

I have looked at the documentation, a bunch of SO threads, but I can't see clearly defined anywhere what persistence is, and where it should be used.

I see it is something to do with checking if a record is new or not, but I don't see why that is useful.

By 'clearly', I mean 'simply enough for a newbie to understand' :)

Ruby - RoR. ActionController::RoutingError (uninitialized constant ...)

Posted: 12 May 2016 06:35 AM PDT

for first sorry for my english.

I've a Rails app with a namespaced route that works fine on localhost but does not work on remote Server.

This is my error:

ActionController::RoutingError (uninitialized constant  Monitor::PapTagsController):  

My routes.rb

namespace :monitor do      resources :pap_tags do        resources :pap_tag_rules      end    end  

file is: pap_tags_controller.rb

class PapTagsController < ApplicationController  ...  end  

It's very strange, can you help me?

thanks.

MIME type is nil after upgrading from Rails 4.2.x to 5

Posted: 12 May 2016 06:01 AM PDT

After upgrading from Rails 4.2.x to 5, whenever I make a call to my controllers the MIME type is nil.

Whenever I log the request.format parameter this is the result: */*. (It doesn't matter whether I call it from a browser or AJAX).

In contrast, when I try to create a new Rails 5 project the correct format is being printed:

#<Mime::Type:0x007fc84301ed58 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html", @hash=-4563418892722065616>  

I've tried reading the upgrade docs, but haven't found anything pertaining to this problem.

Capybara is not finding fields when form has file_field input

Posted: 12 May 2016 05:59 AM PDT

I have a very strange problem with my specs. I have form that looks like this:

= simple_form_for [:admin, @provider] do |f|    = f.input :provider_type_id    = f.input :provider_username    = f.input :first_name    = f.input :last_name    = f.input :athena_health_provider_id    = f.input :display_name    = f.input :specialty    = f.input :entity_type    = f.input :home_department    = f.input :billable    = f.input :npi    = f.input :ansi_specialty_code    = f.input :ansi_name_code    = f.input :languages    = f.input :description    = f.input :photo, as: :file    = f.submit class: 'btn btn-primary'  

And feature spec that looks like this:

require 'rails_helper'    feature 'Provider edit' do    let(:admin)   { create(:user, :admin) }    let(:provider) { create(:provider) }      before do      login_as admin      visit edit_admin_provider_path(provider)    end      context 'when form is filled with invalid data' do      before do        fill_in 'First name', with: nil        click_button 'Update provider'      end        scenario 'redirects to :edit' do        expect(current_path).to eq admin_provider_path(provider)      end        scenario 'contains errors' do        expect(page).to have_text "can't be blank"      end    end  end  

This spec is failing. Capybara is not updating the First name input with nil value. But when I change input to this:

= f.input :photo  

everything works as expected. Why is that?

Two owned stripe accounts on an app (Rails)

Posted: 12 May 2016 05:54 AM PDT

I know there are similar questions to this one, but I haven't found a clear answer. I have an ecommerce that charges to two different stripe accounts (different owners). However, this two accounts are "controlled". This means that I don't have to create charges on behalf of multiple accounts. I'd rather make direct charges to these two accounts.

Knowing this: do I have to set up Stripe Connect? Or can I manage multiple keys for the different accounts? In case I have to use Stripe Connect, how can I create the account so it's hardcoded?

Rails 4 + Devise: Send welcome email with password reset instructions

Posted: 12 May 2016 05:52 AM PDT

I have my registrations set up such that I create the account for a user with a predetermined password, then I would like to send them a welcome email, with a link to the Devise edit_user_password_url.

My method fails because when the User follows the link, they see the following: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."

How can I make my welcome email include the proper link for password reset?

# RegistrationsController  def create       if params[:user] && !params[:user][:password]           params[:user][:password] = "testpassword" #obviously not real           build_resource(sign_up_params)           puts sign_up_params                resource.save              yield resource if block_given?              if resource.persisted?                  if resource.active_for_authentication?                      set_flash_message :notice, :signed_up if is_flashing_format?                      NewUserMailer.new_user_email(resource).deliver_now                      redirect_to users_path                  else                      set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}"                      expire_data_after_sign_in!                      respond_with resource, location: after_inactive_sign_up_path_for(resource)                  end              else                  render :new, :address => params[:address]              end       else           super       end  end    #email   Welcome, follow this link to update your password <%= link_to "My account", edit_user_password_url %></p>  

Memory consumpton inside sidekiq worker

Posted: 12 May 2016 06:32 AM PDT

  1. Does loading multiple Models in sidekiq worker can cause memory leak? Does it get garbage collected?

For example:

class Worker    include Sidekiq::Worker      def perform      Model.find_each do |item|        end    end  end  
  1. Does using ActiveRecord::Base.connection inside worker can cause problems? Or this connection automatically closes?

Getting an undefined method even though I have defined it in my controller

Posted: 12 May 2016 05:54 AM PDT

I'm using Rails 4.2.3. I want to have a tabbed menu on my admin login page, so I added the following to my app/controllers/admin_controller.rb file …

class AdminController < ApplicationController    before_filter :must_be_admin, only: :index      def index      @page_id = "index"    end      def menu_builder(page_id)      tabs = ['Current Hacks','Add New Hack','Approve Hacks']      content = ""      tabs.each do |tab|        content << if page_id == tab          content_tag('li', content_tag('a', tab, :href => nil ), :class => 'current') + " "        else          content_tag('li', content_tag('a', tab, :href => "/#{tab}" )) + " "        end      end      content    end  

Here is what I have in my app/views/admin/index.html.erb file …

<h1>Admin#index</h1>  <ul>      <%= menu_builder(@page_id) %>  </ul>  

However, when I visit my /admin/index page, I get this error

undefined method `menu_builder' for #<#<Class:0x007f861bfe9900>:0x007f861bff36f8>  

Where am I going wrong?

From Parse Push to custom integration

Posted: 12 May 2016 05:24 AM PDT

I'm trying to migrate my Parse handled notifications to a home-made service made in ruby on rails. It was pretty easy to do so with Apple Push Notifications, using rpush gem.

But I discovered that for Android, Parse uses its custom integration, making all the tokens that i have (>1000) invalid with Google Cloud Messaging.

My question is: how can I use Parse tokens in a custom integration with rpush, or from scratch, in Ruby on Rails?

Hope my question is clear enough, don't hesitate to ask me details.

Storing configuration info and accessing it from module

Posted: 12 May 2016 05:58 AM PDT

I'm writing an API (a module in /lib folder). In a sample app, I will use it to store user configuration data such as client_id.

lib/specific_api.rb

module SpecificApi   #client_id and redirect_uri will be accessed from here  end  

controllers/sessions_controller.rb

class SessionsController < ApplicationController   include SpecificApi   CLIENT_ID = "dlfjksldkjfs"   REDIRECT_URI = "http://127.0.0.1:3000/auth"  end  
  1. What should be used to store such info: class, global variables, or constants?

  2. How can these variables be accessed from the API (module included in class)? I could not access the class variables or constants from the module. Global variables work, but I'm not sure if that's a good way to store such info.

rails make select tag remember selection

Posted: 12 May 2016 06:27 AM PDT

I have a form with select

<%= form_tag "?", :method => :get, :class => "form-inline" do %>  <%=select_tag 'brand_name', options_for_select(@brands.collect{ |b| [b.name, b.name] })%>        <button class="btn btn-default " type="submit" value ="search">apply </button>  <%end%>  

It seems to be working. So I want to include blank option with text select brand I tried this:

<%=select_tag 'brand_name', options_for_select(@brands.collect{ |b| [b.name, b.name] }), {:include_blank => 'select brand'}%>

But now This blank option is always selected. For example If I select coca-cola and press submit button I go to the page mysite?brand_name=coca-cola But the selected option in my dropdown blank (select brand) So how can I make it select option coca-cola if I chose coca-cola. Also, how do I add classname to my select?=)

Foreign key display_name in chartkick

Posted: 12 May 2016 04:58 AM PDT

I am working with the Activeadmin and chartkick, I am trying to show the display name of the foreign key since i group the chart with foreign key

here is my code

div class: 'emotion' do  h3 'Recent-Emotion Detected'  @metric = History.group.includes(:emotion_id).count #whatever data you pass to chart  render :partial => "metrics/dashboardemotion" , locals: {metric: @metric}  end  

Creating demo data for rails application on per account basis

Posted: 12 May 2016 05:32 AM PDT

I would like to create some sample data for a user when they register so that they do not have to start with a blank canvas.

I am presently defining lots of static data in classes which I then iterate over, however setting up relationships is cumbersome and I think that this is quite brittle.

I think that having some demo fixtures (separate from my test set) would be a good way to do this, but as records are tied to an account I can't see how I can insert this data and attach it to the account when loading the fixtures.

This might not even be the best approach, but if there is a better way then please let me know.

facing issue with image url in production mode

Posted: 12 May 2016 05:57 AM PDT

i have this type of code

module PhotosHelper     def photo_default_image_url(photo)      if photo.image_url == "/assets/image.jpg"          URI.join(root_url, "/assets/image.jpg")      else          photo.image_url(:thumb)      end    end  end    and image code is      <img src="<%= photo_default_image_url(@photo) %>">  

its working fine for development mood.

i got url like this for image

http://localhost:3000/assets/image.jpg  

but its not working in production mood

i got url like this for image

/image.jpg  

please help me to solve this. thank you

session variable is not recognized anymore after migrating js code to assets/javascripts in rails app

Posted: 12 May 2016 06:04 AM PDT

I moved some javascript that was in a content_for(:after_js) at the end of an html page to a proper js file inside my assets/javascripts folder in my rails app. I created a js.erb file that looks like this :

 <% if session[:user_role] == "asso" %>      <%= render "javascripts/select_bar/_select_bar_asso.js"%>   <% else %>      <%= render "javascripts/select_bar/_select_bar_host.js"%>    <% end %>  

but now I always get the error :

undefined local variable or method `session' for #<#:0x007feb90e24400>.

It was working fine when the js was in the content_for(:after_js) at the end of my html.erb file and it was ok with the session variable.

What did I do wrong with my javascript migration ?

rails find <Item:0x007fa154cc5860>

Posted: 12 May 2016 04:19 AM PDT

I am trying to debug my rails app in production mode. So I want to see which item from database I get but when I write in my view <%= a %> it shows me <Item:0x007fa154cc5860>.

When I write <%= a.id %> I get the error undefined method id for nil:NilClass.

How do I find this <Item:0x007fa154cc5860> item ?

Controller:

#analogs  @analogs = []    @analogs_codes.each do |code|    i = Item.where(:code => code).first    if i != nil?       @analogs << i    end   end  

And view:

<% @analogs.each do |a| %>    <%= a.id %>  <% end %>  

Best practice: Rails paginate biggish data with partitioned table

Posted: 12 May 2016 03:56 AM PDT

If I have a table partitioned and indexed by created at time in 6 months like this:

 posts_2014_01_01_to_2014_05_30   posts_2014_06_01_to_2014_12_30   posts_2015_01_01_to_2015_05_30   posts_2015_06_01_to_2015_12_30  

When I do Rails pagination it will generate query like this, but is this be slow to run since the partition indexed column is not reference in the where clause? and will it touch all tables?

  SELECT  "posts".* FROM "posts" LIMIT 10 OFFSET 1,000,000  

Some people suggest to use range search to paginate biggish data, isn't that the same to just put the partitioned index column in the where clause like this?

   SELECT  "posts".* FROM "posts" where created_at > '2014/12/30' LIMIT 10 OFFSET 1,000,000  

Any suggestion on perform pagination on biggish table using GEM Kaminari or will_paginate?

Use of delay in ActiveJobs

Posted: 12 May 2016 03:42 AM PDT

I'm trying to move my rails app's background processing library from DelayedJob to SideKiq. I went through the documentation for ActiveJobs and for Sidekiq, both of which suggest either a app/workers folder or app/jobs folder with the a perform method being written and further calling a class method such as perform_async.

However, on just adding the SideKiq gem, adding Sidekiq as the value for config.active_job.queue_adapter the following seems to work: delay(queue: queue_name , other_parameters ).method

Where is delay defined? Is it an alias for perform? I tried searching for it in Rails' repo but to no avail.

Deploying error with capistrano: "bundler: not executable: cap"

Posted: 12 May 2016 03:43 AM PDT

I am supposed to work on a quite antique Ruby On Rails project to make some minor (mostly HTML and CSS) changes on some webpages. I did not work with Ruby On Rails before and I am just getting into it.

I have cloned the project via git from github and installed all gems via 'bundler install'. Note that I am using an old version of Ruby (1.8.7) since I was told the project would not work with a newer version. Note also I am on Windows 7 and the project was built with Mac OS X.

Now I am trying to get the changes I made to the live site (after commiting and pushing the changes to the git repository) with Capistrano (Installed and Version 2.8.0) which should be possible with

bundle exec cap production deploy  

However when I try this I just get:

bundler: not executable: cap  

Any ideas what is going wrong here? Thanks alot in advance!

Kind regards, Peter

Rails Paperclip and aws s3 integration error "uninitialized constant Paperclip::Storage::S3::Aws"

Posted: 12 May 2016 05:50 AM PDT

I have gone through different posts but got no help, I am trying to upload my images to Amazon S3 I double checked my asw credentials they all are correct, here are the required files please help

Gemfile

gem 'aws-sdk', '< 2.0'  gem 'devise'  gem "paperclip", "~> 5.0.0.beta1"  gem 'bootstrap-sass', '~> 3.3.6'  gem 'bootstrap-material-design'  gem 'nested_scaffold'    

config/environments/development.rb

  # Raises error for missing translations    # config.action_view.raise_on_missing_translations = true    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }    config.action_mailer.delivery_method = :smtp      config.paperclip_defaults = {    storage: :s3,    s3_credentials: {      bucket: "bucketName",      access_key_id: "xoxoxo",      secret_access_key: "secret_key"      }  }  

config/initializers/paperclip.rb

# config/initializers/paperclip.rb  Paperclip::Attachment.default_options[:url] = ':s3_domain_url'  Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'  Paperclip::Attachment.default_options[:s3_host_name] = 's3-us-west-2.amazonaws.com'  

And while uploading Iam still getting the error

NameError in CorporateTrainersController#create uninitialized constant Paperclip::Storage::S3::Aws

Extracted source (around line #29):              # POST /corporate_trainers.json    def create      @corporate_trainer = CorporateTrainer.new(corporate_trainer_params)        respond_to do |format|        if @corporate_trainer.save  

Is there a way to Get retweets of all tweets in one call?

Posted: 12 May 2016 03:14 AM PDT

I want to know how many retweets were done for my tweets? I guess this can do it, https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me

But the problem is that above function is not in the twitter gem, so how to do it?

in twitter gem we have this function:

client.user_timeline(userid)  

but there is no function such as

client.retweets_of_me  

so how to do it?

"render :partial" can't find files when called on its own

Posted: 12 May 2016 05:34 AM PDT

I have a rails 2.2.2 app with the following odd problem.

There's a .js.rjs file, which is rendered to produce javascript as the response to a .js format query.

If i do this, it works fine:

page.replace_html "search-results-resources-paginated", :partial => "search/discover_results"  

Ie, it renders out the app/views/search/_discover_results.html.erb partial (which in turn calls other partials). That's all working fine.

However, I want to break this down into a couple of steps, where i render the partial into a text string, and then use that string in the javascript (i just want to do this for a bit of extra debugging).

I'm trying to do this like so:

text = render(:partial => "search/discover_results")  page.replace_html "search-results-resources-paginated", :text => text  

this is now starting to complain about not being able to find the partial:

ActionView::TemplateError (Missing template search/_discover_results.erb in view path     /app/views:    <project folder>/app/views/community:    <project folder>/vendor/plugins/savage_beast/app/views:    <project folder>/vendor/plugins/exception_notification/app/views:    <project folder>/vendor/plugins/query_reviewer/lib/query_reviewer/lib/query_reviewer/views:  ) on line #49 of app/views/search/discover.js.rjs:  

(i've formatted the above a little, for clarity)

If i tell render the actual file extension, like so:

text = render(:partial => "search/discover_results.html.erb")  

then it finds that first partial, but i get the same problem with other partials this it references. It's like render doesn't know that it's supposed to be looking for html.erb files, rather than just .erb files.

Is there an extra option i need to pass to render to make this work?

thanks, Max

Ruby on Rails server DB to share in Java Swing Desktop Application

Posted: 12 May 2016 04:41 AM PDT

Namaskaram, I am developing a Task Management application to work on both mobile and Desktop. I have selected Java Swing framework for Desktop and Android for Mobile Application respectively.

The server developed in Ruby on Rails.

I want to share Database of server to my Java Swing Desktop Application.

I have no idea, how to connect Ruby on Rails server database to Java Swing application. Please help me.

Rails: ActiveRecord:RecordNotUnique with first_or_create

Posted: 12 May 2016 04:58 AM PDT

I have this index in my Model's table:

UNIQUE KEY `index_panel_user_offer_visits_on_offer_id_and_panel_user_id` (`offer_id`,`panel_user_id`)  

And this code:

def get_offer_visit(offer_id, panel_user_id)    PanelUserOfferVisit.where(:offer_id => offer_id, :panel_user_id => panel_user_id).first_or_create!  end  

is randomly causing an ActiveRecord::RecordNotUnique exception in our application, the issue is:

Duplicate entry for key 'index_panel_user_offer_visits_on_offer_id_and_panel_user_id'

I've read on the rails doc that first_or_create! is not an atomic method and can cause this kind of issues in a high concurrency environment and that a solution would be just to catch the exception and retry.

I tried different approaches, including Retriable gem to retry a certain number of times to repeat the operation but RecordNotUnique is still raised.

I even tried to change the logic:

def get_offer_visit(offer_id, panel_user_id)    begin      offer_visit = PanelUserOfferVisit.where(:offer_id => offer_id, :panel_user_id => panel_user_id).first_or_initialize      offer_visit.save!              offer_visit      rescue ActiveRecord::RecordNotUnique      offer_visit = PanelUserOfferVisit.where(:offer_id => offer_id, :panel_user_id => panel_user_id).first      raise Exception.new("offer_visit not found") if offer_visit.nil?        offer_visit    end  end  

But the code still raise the custom exception I made and I really don't understand how it can fails to create the record on the first try because the record exists but then when it tries to find the record it doesn't find it again.

What am I missing?

Using Ruby on Rails [on hold]

Posted: 12 May 2016 02:58 AM PDT

i'm new to ruby on rails and im trying to create basic website i have already designed and built Template using bootstrap but now i want to add the backend stuff i.E write post , show post. ive gone over codecademy etc and i have set up & installed ruby on rails on my machine and its all working i just cant seem to get my head around how to create pages & how to make things 'work' lol all tutorials out there seem to just show you how to load a blog in 10 mins but seem to miss most of the basics for somebody really new to it

I18n not loading translations with apartment gem rails

Posted: 12 May 2016 03:09 AM PDT

I am making a multi tenancy app using the apartment gem. I have it all set up and everything works as expected. I'm also using Rails Internationalization (I18n) with active record backend to store translations. My current setup

Translation Table

class CreateTranslations < ActiveRecord::Migration[5.0]    def change      create_table :translations do |t|        t.string :locale        t.string :key        t.text :value        t.text :interpolations        t.boolean :is_proc, default: false          t.timestamps      end    end  end  

Apartment.rb configuration

I've added the Translation model to the list of excluded models so its global across all tenants

Apartment.configure do |config|      # Add any models that you do not want to be multi-tenanted, but remain in the global (public) namespace.    # A typical example would be a Customer or Tenant model that stores each Tenant's information.    #    config.excluded_models = %w{ User Workspace Translation }  end  

In my translations table I have translations for both English (default) and Norwegian. On the main domain everything works as expected switching between English and Norwegian but all translations go missing once I load a tenant. Demo in console:

> Apartment::Tenant.switch! # switch to main tenant  > I18n.locale = :en # use English translations  > I18n.t('home.members_label')    => "Show Members"    > Apartment::Tenant.switch! "elabs" # switch to a different tenant  > I18n.t('home.members_label')    => "translation missing: en.home.members_label"  

I'm not sure why translations are missing when in a tenanted environment. I was figuring having the Translation model in the list of excluded_models should do the trick but it seems something is wrong somewhere. Any clues? Thanks

type="email" doesn't check all cases

Posted: 12 May 2016 03:01 AM PDT

I am using type="email" for email validation . When I enter email like this dfg@fsdfafasf it doesn't give any error.

How I check this?

No comments:

Post a Comment