Monday, November 7, 2016

Change attribute label value | Fixed issues

Change attribute label value | Fixed issues


Change attribute label value

Posted: 07 Nov 2016 07:58 AM PST

I'm sure this has already been asked and it's pretty easy but I don't really know what to search to find a solution.

If I have values in a column table like 1,-1,2 where -1 = sale, 1 = purchase etc, how do I show purchase instead of 1 or sale instead of -1?

Database table stockmovements column name reason.

Rails Form Example

Posted: 07 Nov 2016 07:43 AM PST

I'm new to forms in Rails so this may be a very basic question.

I have an HTML page that I would like to turn into a basic form:

<div class="container">      <div class="row">          <div class="col-sm-12">              <h2>What is your age?</h2>              <input type="number" id="age"><br>          </div>          <div class="col-sm-12">              <h2>What is your zip code?</h2>              <input type="number" id="zip"><br>          </div>          <div class="col-sm-12">              <h2>What is your gender?</h2>              <select id="gender">                  <option></option>                  <option value="42198">Male</option>                  <option value="42199">Female</option>              </select>          </div>          <div class="col-sm-12">              <h2>Are you of Hispanic, Latino, or Spanish origin?</h2>              <select id="hispanic">                  <option></option>                  <option value="42200">No , not of Hispanic, Latino, or Spanish origin</option>                  <option value="42201">Yes, Mexican, Mexican American, Chicano</option>                  <option value="42202">Yes, Cuban</option>                  <option value="42203">Yes, another Hispanic, Latino, or Spanish origin *** Argentina</option>                  <option value="42204">Yes, another Hispanic, Latino, or Spanish origin *** Colombia</option>                  <option value="42205">Yes, another Hispanic, Latino, or Spanish origin *** Ecuador</option>                  <option value="42206">Yes, another Hispanic, Latino, or Spanish origin *** El Salvadore</option>                  <option value="42207">Yes, another Hispanic, Latino, or Spanish origin *** Guatemala</option>                  <option value="42208">Yes, another Hispanic, Latino, or Spanish origin *** Nicaragua</option>                  <option value="42209">Yes, another Hispanic, Latino, or Spanish origin *** Panama</option>                  <option value="42210">Yes, another Hispanic, Latino, or Spanish origin *** Peru</option>                  <option value="42211">Yes, another Hispanic, Latino, or Spanish origin *** Spain</option>                  <option value="42212">Yes, another Hispanic, Latino, or Spanish origin *** Venezuela</option>                  <option value="42213">Yes, another Hispanic, Latino, or Spanish origin *** Other Country</option>                  <option value="42214">Prefer not to answer</option>              </select>          </div>          <div class="col-sm-12">              <h2>What is your race?</h2>              <select id="ethnicity">                  <option></option>                  <option value="42215">White</option>                  <option value="42216">Black, or African American</option>                  <option value="42217">American Indian or Alaska Native</option>                  <option value="42218">Asian *** Asian Indian</option>                  <option value="42219">Asian *** Chinese</option>                  <option value="42220">Asian *** Filipino</option>                  <option value="42221">Asian *** Japanese</option>                  <option value="42222">Asian *** Korean</option>                  <option value="42223">Asian *** Vietnamese</option>                  <option value="42224">Asian *** Other</option>                  <option value="42225">Pacific Islander *** Native Hawaiian</option>                  <option value="42226">Pacific Islander *** Guamanian</option>                  <option value="42227">Pacific Islander *** Samoan</option>                  <option value="42228">Pacific Islander *** Other Pacific Islander</option>                  <option value="42229">Some other race</option>                  <option value="42230">Prefer not to answer</option>              </select>          </div>          <div class="col-sm-12">              <h2>What is your relationship status?</h2>              <select id="standard_relationship">                  <option></option>                  <option value="42231">Single, never married</option>                  <option value="42232">Married</option>                  <option value="42233">Separated, divorced or widowed</option>                  <option value="42234">Domestic partnership/living with someone</option>                  <option value="42235">Prefer not to answer</option>              </select>          </div>          <div class="col-sm-12">              <h2>What is the highest level of education you have completed?</h2>              <select id="standard_education">                  <option></option>                  <option value="42236">3rd Grade or less</option>                  <option value="42237">Middle School - Grades 4 - 8</option>                  <option value="42238">Completed some high school</option>                  <option value="42239">High school graduate</option>                  <option value="42240">Other post high school vocational training</option>                  <option value="42241">Completed some college, but no degree</option>                  <option value="42242">Associate Degree</option>                  <option value="42243">College Degree (such as B.A., B.S.)</option>                  <option value="42244">Completed some graduate, but no degree</option>                  <option value="42245">Masters degree</option>                  <option value="42246">Doctorate degree</option>                  <option value="42247">None of the above</option>              </select>              <h2>How much total combined income do all members of your household earn before taxes?</h2>          </div>          <div class="col-sm-12">              <select id="standard_hhi_us">                  <option></option>                  <option value="43490">Less than $5,000</option>                  <option value="43491">$5,000 to $9,999</option>                  <option value="43492">$10,000 to $14,999</option>                  <option value="43493">$15,000 to $19,999</option>                  <option value="43494">$20,000 to $24,999</option>                  <option value="43495">$25,000 to $29,999</option>                  <option value="43496">$30,000 to $34,999</option>                  <option value="43497">$35,000 to $39,999</option>                  <option value="43498">$40,000 to $44,999</option>                  <option value="43499">$45,000 to $49,999</option>                  <option value="43500">$50,000 to $54,999</option>                  <option value="43501">$55,000 to $59,999</option>                  <option value="43502">$60,000 to $64,999</option>                  <option value="43503">$65,000 to $69,999</option>                  <option value="43504">$70,000 to $74,999</option>                  <option value="43505">$75,000 to $79,999</option>                  <option value="43506">$80,000 to $84,999</option>                  <option value="43507">$85,000 to $89,999</option>                  <option value="43508">$90,000 to $94,999</option>                  <option value="43509">$95,000 to $99,999</option>                  <option value="43510">$100,000 to $124,999</option>                  <option value="43511">$125,000 to $149,999</option>                  <option value="43512">$150,000 to $174,999</option>                  <option value="43513">$175,000 to $199,999</option>                  <option value="43514">$200,000 to $249,999</option>                  <option value="43515">$250,000 and above</option>                  <option value="43516">Prefer not to answer</option>              </select>          </div>      </div>  </div>  

Basically on clicking the <input type="submit"> button, I would like to make a POST to my

example#post_action

In that call I would like to pass in the values of all of my fields.

So the #age numeric value, and the values of the selected dropdown, so #gender might have a value of 42198 if Male is selected, etc.

What's the most appropriate way to define this type of a form in Rails? Giving that this isn't for a specific user, I can't really do a form_for call here, as these values will not be stored directly in columns.

Create object and make payment with stripe

Posted: 07 Nov 2016 07:15 AM PST

So I am trying to create a job object in jobs_controller and I have managed to get the checkout stripe gem to work as described here. So I can make a payment in mywebsite/charges/new , so the api keys are correct and working as I can see my test payments in the stripe dashboard.

But I now want to create a payment as the user is trying to create a job object, as you can see in the create action inside my jobs_controller.

def create      @job = Job.new(job_params)      @job.highlight = true        raise "Please, check job errors" unless @job.valid?      @amount = 200 *100          customer = Stripe::Customer.create(          :email => params[:stripeEmail],          :source  => params[:stripeToken]      )        charge = Stripe::Charge.create(          :customer    => customer.id,          :amount      => @amount,          :description => 'Rails Stripe customer',          :currency    => 'usd'      )        @job.save      redirect_to @job, notice: 'Job was successfully created.'      rescue Stripe::CardError => e      logger.debug e.message      flash[:error] = e.message      render :new  end  

And my _form.html.erb in /jobs

    <form>    <%= form_for(job) do |f| %>        <% if job.errors.any? %>            <div id="error_explanation">              <h2><%= pluralize(job.errors.count, "error") %> prohibited this job from being saved:</h2>                <ul>                <% job.errors.full_messages.each do |message| %>                    <li><%= message %></li>                <% end %>              </ul>            </div>        <% end %>          <div class="form-group">          <%= f.label :title %><br>          <%= f.text_field :title, :class => "form-control" %>        </div>          <div class="form-group">          <%= f.label :description %><br>          <%= f.bootsy_area :description, size: "100x30", :class => "form-control", editor_options: { font_styles: false, image: false, color: false } %>        </div>          <div class="form-group">          <%= f.label :url %><br>          <%= f.text_field :url, :class => "form-control" %>        </div>          <div class="form-group">          <%= f.label :company %><br>          <%= f.text_field :company, :class => "form-control" %>        </div>          <div class="form-group">          <label>By posting a job, you agree to our <%= link_to "terms of service policy.", terms_path %></label>        </div>          <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"                data-key="<%= Rails.configuration.stripe[:publishable_key] %>"                data-description="A job posting"                data-amount="20000"                data-locale="auto">          </script>    <% end %>  </form>  

But when I try to create a job the payment wont go trough and no object is created and I cant see any errors coming out, I dont see any thing in the heroku logs either so I am lost. Any ideas of where my problem is?

Thank you.

Devise from 2.2.4 to 4.2.0

Posted: 07 Nov 2016 07:35 AM PST

I'm upgrading Rails 3.2.22.2 app to Rails 4.2.7.1. In the process, I am updating Devise from 2.2.4 to 4.2.0. I've searched numerous posts here and elsewhere to answer two questions:

  1. In this scenario are there any 'gotchas' that need to be taken care of first before I try to get this working?
  2. rails generate devise:install generates undefined method token_authentication_key= for Devise:Module (NoMethodError)

In devise.rb initializer I have:

config.token_authentication_key = :auth_token  

In Gemfile:

gem 'devise'  gem 'devise-encryptable'  gem 'devise-token_authenticatable', '~> 0.5.0'  

In my user.rb model:

devise :database_authenticatable, :token_authenticatable, :registerable,   :recoverable, :trackable, :encryptable,   :encryptor => :restful_authentication_sha1  

users table fields:

t.string   "encrypted_password", :limit => 128, :default => "",    :null => false  t.string   "password_salt",                     :default => "",    :null => false  

Thanks!

rake task will run twice when ActiveJob in it

Posted: 07 Nov 2016 07:10 AM PST

class PushToUserJob < ApplicationJob    queue_as :default    def perform(*args)      puts 'perform ..'    end  end    namespace :push do    task check: :environment do      puts 'exec check ...'      PushToUserJob.perform_later('5')    end      task test: :environment do      puts 'exec test ..'    end  end  

run rake push:test, it print one line 'exec test ...', it is ok.

but when run rake push:check, it print two lines

'exec check ...'    'exec check ...'  

why it print twice ?

and i remove "PushToUserJob.perform_later('5')",it print once again!

How to handle multiple exceptions in a Transaction with Ruby on Rails for importing a text file

Posted: 07 Nov 2016 07:48 AM PST

My ruby environment is: Ruby 2.3.1 and Rails 5.0.0.1.

I'm trying to import a text file for import a lot of purchases items.

Example of purchase file:

data.txt

Customer\tDescription\tUnit Price\tQuantity\tAddress\tSupply company\n Athos Matthew\tChocolate\t10\t5\tSome address.\tChocolate company\n

The columns are divided by a tab (\t) and it has an enter at the final (\n).

I have the purchase class where all attributes cannot be null. The attributes are:

custumer_name:string  product_id:integer        # It has relationship with the Product Resource  product_quantity:integer  supply_company_id:integer # It has relationship with the SupplyCompany Resource  

To import the file, I decided to create a PurchaseImporter class to do this job and keep the code cleaner.

My problem is that transaction part:

  begin      ActiveRecord::Base.transaction do        purchase = Purchase.new        data = line.force_encoding('UTF-8').split(/\t/)          purchase.customer_name = data[0]        product = Product.find_or_create_by!(description: data[1], price: data[2])        purchase.product_quantity = data[3]        purchase.product = product        supply_company = SupplyCompany.find_or_create_by!(name: data[5], address: data[4])        purchase.supply_company = supply_company          purchase.save!      end    rescue Exception => e      @errors[:import][index] = e.message    end  

My problem is that I want to catch all the raised errors from the Product, SupplyCompany and Purchase that could happen inside this transaction.

This is the order of the happenings without the unnecessary code to explain it.

product = Product.find_or_create_by!(description: data[1], price: data[2])  supply_company = SupplyCompany.find_or_create_by!(name: data[5], address: data[4])  purchase.save!  

I need to print this errors information to this 3 classes in the screen, but with my code, I can only catch the first exception error, generated by the product. If some error happened in the SupplyCompany or in the Purchase, I lost these errors messages.

Are there other ways to import and log the errors message when importing files?

Rails 4.2 Polymorphic associations, association name not resolving

Posted: 07 Nov 2016 06:59 AM PST

I created the migration according the polymorphic rails cookbook. The models have the following relations

class TeachingAssistant < ActiveRecord::Base    belongs_to :ta_type, polymorphic: true  end    class University < ActiveRecord::Base    has_many :teaching_assistants, as: :ta_type  end  

In the rails console i am able to do the following

t = TeachingAssistant.create name: 'name'   u = University.create name: 'hogwarth'   t.update ta_type: u   University.last.teaching_assistants.last  

But why is it not possible to use the as: :ta_type association name directly;

University.last.ta_type  

results for example in undefined method for ta_type. But typing

University.last.ta_type  

and tab-completing returns the following list

University.last.ta_type      University.last.ta_type=             University.last.ta_type_id          University.last.ta_type_id=                     University.last.ta_type_id?                    University.last.ta_type_id_before_type_cast     University.last.ta_type_id_came_from_user?        University.last.ta_type_id_change                University.last.ta_type_id_changed?              University.last.ta_type_id_was         ....  

Why is this not possible? Is it by design or am i doing something wrong?

Re-render a page using jquery

Posted: 07 Nov 2016 06:59 AM PST

In react, I could easily re-render a view by passing results from controller. I wish not to use React at this stage and was wondering if it's possible with JQuery?

I have few objects on page, and when clicked, I should see its content. Click the other object, I see its content etc. Sense? I was inspired by this dribbble.

I may not be doing this the right way but this is what I have:

Controller:

def index    selected_contract = params[:selected_contract] || current_user.contracts.last.id    @contracts = current_user.contracts.order(created_at: :desc).all    @selected_contract = current_user.contracts.find_by(id: selected_contract)  end  

View:

<% @contracts.each do |contract| %>    <button class="ui button test" id="<%=contract.id%>"><%=contract.name%></button>  <% end %>    ......................................  When clicked, show its content  ....................................    <%= @selected_contract.name %>  

JS:

$( ".ui.button.test" ).click(function(e) {    let { id } = this    console.log(id)    $.ajax({      url: `/url/${id}`,      type: 'POST',      success: function(result) {        //$('#listview').redraw()        console.log('success')      }    });  });  

Routes are set properly so I get the params in the controller just fine. Is there a re-render a view, just like rerender a prop in React for jquery? Am I doing this the correct way?

How do I drop a foreign key if it exists in Ruby on Rails?

Posted: 07 Nov 2016 07:06 AM PST

There's a function called index_exists? in ActionRecord, but no foreign_key_exists? on Rails 4.2.7.

So when I call remove_foreign_key :parties, :franchise_groups on some databases it breaks.

What should I use?


Update

My code

class RemoveForeignKey < ActiveRecord::Migration    def up      if foreign_key_exists?(:parties, :franchise_groups)        remove_foreign_key :parties, :franchise_groups      end    end  end  

gives the error

== 20161107163800 RemoveForeignKey: migrating =================================  -- foreign_key_exists?(:parties, :franchise_groups)  rake aborted!  An error has occurred, all later migrations canceled:    undefined method `foreign_key_exists?' for #<RemoveForeignKey:0x00000007ea0b58>  /home/rje/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7/lib/active_record/migration.rb:664:in `block in method_missing'  

How to create a profile for devise user?

Posted: 07 Nov 2016 06:50 AM PST

I'm new to rails and trying to create a profile for devise users when they signup, using nested form in devise signup. I've gone through Creating Profile for Devise users, Profile model for Devise users? and few other articles to achieve the same but after a day in vain, I'm still trying to make it work. Here is my code.

Model - user.rb

class User < ActiveRecord::Base    has_one :user_profile    accepts_nested_attributes_for :user_profile      # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end  

Model - user_profile.rb

class UserProfile < ActiveRecord::Base    belongs_to :user  end  

Controller - controllers/users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController    def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_up) {|u|         u.permit(:email, :password, :password_confirmation, :remember_me,         user_profile_attributes: [:first_name, :last_name])}      end    end  end  

View - views/devise/registrations/new.html.erb

 <h2>Sign up</h2>   <% resource.build_user_profile %>   <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>     <%= devise_error_messages! %>       <div class="field">       <%= f.label :email %><br />       <%= f.email_field :email, autofocus: true %>     </div>       <div class="field">       <%= f.label :password %>       <% if @minimum_password_length %>         <em>(<%= @minimum_password_length %> characters minimum)</em>       <% end %><br />       <%= f.password_field :password, autocomplete: "off" %>     </div>       <div class="field">       <%= f.label :password_confirmation %><br />       <%= f.password_field :password_confirmation, autocomplete: "off" %>     </div>       <%= f.fields_for :user_profile do |profile_form| %>       <%= profile_form.label :first_name %><br/>       <%= profile_form.text_field :first_name %><br/>         <%= profile_form.label :last_name %><br/>       <p><%= profile_form.text_field :last_name %><br/>     <% end %>       <div class="actions">       <%= f.submit "Sign up" %>     </div>   <% end %>     <%= render "devise/shared/links" %>  

Server Log

Processing by Devise::RegistrationsController#create as HTML    Parameters: {"utf8"=>"√", "authenticity_token"=>"rLuFXwISxiJpWPjpmKzjnjhKr41F5  56sWbtT+8gslAMsFDWRbl7MSitSXUESjLdZccCBGBGvVv+JbhW7G5py5g==", "user"=>{"email"=>  "zebandz@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTER  ED]", "user_profile_attributes"=>{"first_name"=>"Zeban", "last_name"=>"Dezend"}}  , "commit"=>"Sign up"}  Unpermitted parameter: user_profile_attributes  

I think, I'm missing the code to fetch the values from params and create a new record. Can someone suggest me the fix ?

how to use role authorization for micro services architecture?

Posted: 07 Nov 2016 06:23 AM PST

I wrote an API in rails which is of micro services architecture. In my API i need to implement Role authorization to authorize each and every user using their roles. Is there any gem that fits into micro services architecture or should I write my own logic to authorize users. i was using gem authorization gem but it does provide much capability that fits into micro services architecture.(rolify) Is there any other that suits micro services architecture?

Thanks in Advance.

best_in_place gem usage in Rails Admin

Posted: 07 Nov 2016 06:46 AM PST

How I can use https://github.com/bernat/best_in_place for in-place editing in Rails Admin list view? For example, I have list of questions and I need edit body of each question directly from list view. PS I found some discussion about this: https://github.com/sferik/rails_admin/issues/1818 but it's not clear for me how setup RailsAdmin for in place editing

Rails ActiveJob Dry Runs

Posted: 07 Nov 2016 06:10 AM PST

I need to enable some "dry-run" option for some of my ActiveJobs.

For my specific case, I need to run "chase" jobs for users that have not replied to a message after x days (amongst other conditions)

I already have feature tests that should take care of the majority of cases, but I'd like to try and detect potential corner-cases I'd have forgotten, by launching a dry run on my production database, and maybe sample the results.

I am wondering how to best do that, and the solution I came up with involves modifying every perform() method to add an option hash (where I would pass dry_run: true that skips the execution).

I am also wondering how to best make the results of the dry-run available. Ideally someone from the Rails web interface should be able to see the logs or whatever output was produced by the job. Any idea that would be better than parsing a logfile ? :S

Rails select_tag undefined method `map' for nil:NilClass

Posted: 07 Nov 2016 06:33 AM PST

I have my problem, kinda solved, but I think its a bit clumsy way, so hope to get a better way, as well as a better understanding whats going on here.

_form.html.erb:

 <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select one!") %>  

products_controller.rb:

def new    @product = Product.new    @categories = Category.all.map { |c| [ c.name, c.id ] }  end  

If user submits form without selecting any of the select_tag options he gets undefined method 'map' for nil:NilClass error.

I know that it comes since my @categories is nil, but I cant figure how to avoid that..?

My final solution, that is working:

<%= select_tag(:category_id, options_for_select(@categories || Category.all.map { |c| [ c.name, c.id ] }), :prompt => "Select one!") %>  

But I feel there is a better way. Also I think, that by assigning a default select_tag value with :selected might work as well, but I couldnt implement it with my knowledge of Ruby syntax...

Rails: Can I spool off a column as a table in its own right?

Posted: 07 Nov 2016 05:53 AM PST

I'm using a model to track my dupermarket purchases. The schema of the table representing items is:

CREATE TABLE "items"   ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,    "barcode" varchar,    "brand" varchar,    "gendesc" varchar,    "size" float,    "unit_id" integer,    "created_at" datetime NOT NULL,    "updated_at" datetime NOT NULL);  

Inclusion of gendesc (generic description, as a varchar) was a modeling mistake; I should have made this a foreign key, with the text descriptions in an additional table, as different brands of the same thing are equivalent for some but not all purposes of analysis. So I want to replace the gendesc column with a gendescs_id column that is a foreign key for some gedescs table which would be equivalent to something created thus:

create table gendescs (id integer primary key, gendesc varchar);    select into gendescs(gendesc) distinct gendesc from items;  

Is there a sequence of Rails migrations which does something like this?

reduce duplication in rails mvc/form/views

Posted: 07 Nov 2016 05:40 AM PST

Can upload images & videos independently (only want one at a time but with choice to be either file type) There is duplication in each view file for image and video as well as in Model (initially to test upload works for both file types) Want to encapsulate in to one element/tag/file/type whatever is correct, tried using 'attachment' to encapsulate both, this did not work and specific video_tag & image_tag seem necessary (please correct me if not the case) Have been spiking.

Any help/ideas how to refactor the duplication appreciated?

Contacts model:

has_attached_file :image, styles: {thumb: "300x300>"}, border:{thumb: "1px solid #ddd"}      validates_attachment_content_type :image, { content_type: ["image/jpeg", "image/gif", "image/png", "image/jpg"] }      has_attached_file :video, styles: { :medium => { :geometry => "300x300>", :format => 'mov', :time => 10 }        }, :processors => [:transcoder]      validates_attachment_content_type :image, { content_type: ["video/mpeg", "video/mov", "video/wmv", "video/mp4", "video/qt", "video/mng", "video/avi"] }  

new.erb (note the duplication for file_field and have two tags image/video when wanting to encapsulate as one)

<div class="polaroid" >      <div class="container">          <div>            <%= f.file_field :image %>            <%= image_tag(:image_url) %>          </div>          <div>            <%= f.file_field :video %>            <%= video_tag(:video_url) %>          </div>      </div>  </div>  <br />  <br />    <%= f.submit %>  

show.erb (duplicated lines dealing with image and email)

<p><%= image_tag @contact.image.url(:thumb) %></p>  <p><%= video_tag @contact.video.url(:medium), :width=>300, :controls => true, :autoplay => true, :loop => true, :class=>"work"  %></p>  

index.erb (again duplicated link_to for both tags)

  <div class="polaroid" >      <div class="container">        <%= link_to image_tag(contact2.image.url(:thumb), :class=> "work" ), contact_path(contact2) %>        <%= link_to video_tag(contact2.video.url(:medium), :size => "250x250", :autoplay => true, :loop => true, :class=>"work" ), contact_path(contact2) %>          <h3><%=contact2.firstname%> <%=contact2.surname%></h3>  

Implement closest friends in Rails api

Posted: 07 Nov 2016 05:39 AM PST

I am building an android app that consumes directly from a rails api. I have a user model already. How do I implement in the rails api such that a user can interact with other users that are closed by within a defined distance?

nginx assets in subfolders

Posted: 07 Nov 2016 06:35 AM PST

I was wondering if there is a better way to define assets path in nginx. For example, I want nginx to serve assets in subfolders. For now, I use this technique which does not look very dry to me.

location ^~ /assets/ {      gzip_static on;      expires max;      add_header Cache-Control public;  }    location ^~ /assets/downloads {      gzip_static on;      expires max;      add_header Cache-Control public;  }  

Could you suggest something better for folders inside assets folder? Thank you in advance.

unread gem doesn't insert base class for public activity

Posted: 07 Nov 2016 05:51 AM PST

I have been trying to get the unread gem work with public activity. I followed this thread here on SO. When I mark the activities as read the readable_type in the read_marks-table is not Activity as expected. It is PublicActivity::ORM::ActiveRecord::Activity.

Obviously I can not retrieve any activities through PublicActivity::ORM::ActiveRecord::Activity.unread_by(current_user) which will give me a NoMethodError. Activity.unread_by(current_user) always spits out the same result since the readable_type doesn't match.

Here are my two models:

# app/models/activity.rb  class Activity < PublicActivity::Activity    acts_as_readable :on => :created_at  end    # app/models/user.rb  class User < ApplicationRecord    acts_as_reader  end  

Now I loop through the activities and get all records from the activities table, mark them and get the above mentioned result:

Activity.unread_by(current_user).each do |obj|    obj.mark_as_read! :for => current_user  end  

So I'm wondering how I will get Activity as readable_type into the database. Or any other work around for that matter.

Thank you.

EDIT:

AH! It was the readable_type field having a limit of only 20 that was truncating my class name. Now it works after I increased the size.

What he then writes in his second update kinda confuses me. I also increased the size to 255 chars but that doesn't seem to be the problem. PublicActivity's base_class seems to be PublicActivity::ORM::ActiveRecord::Activity.

How do I browse folder using simple_form?

Posted: 07 Nov 2016 05:36 AM PST

I want to add a file/folder browsing button in my rails application using simple_form gem. How do I do it? In simple_form documentation it is not mentioned.

selenium webdriver - Connecting enr.rb with Steps

Posted: 07 Nov 2016 06:40 AM PST

I am relatively new to ruby and selenium driver. I have found some ruby code for the ENV.rb file:

require 'rubygems'  require 'selenium-webdriver'      # Catch Error if the browser does not load correctly    def print_error    puts "\nInappropraite browser \"#{ENV['BROWSER']}\""    puts "\nUsage : cucumber BROWSER=browser_name"    puts "\nbrowser_name can be one of following :"    puts "1.ie\n2.chrome\n3.ff\n4.safari\n5.opera"  end    case ENV['BROWSER']    when 'ie'      browser_type = :ie    when 'ff'      browser_type = :ff    when 'chrome'      browser_type = :chrome    when 'opera'      browser_type = :opera    when 'safari'      browser_type = :safari    else      if ENV['BROWSER']        print_error # Print out Error Code if the Browser Doesn't Load      end      browser_type = :ff # CURRENT BROWSER TO LOAD  end    begin    driver = Selenium::WebDriver.for(browser_type) # Load Browser Specified in case    driver.navigate.to 'https://website/contact_us'    #driver.manage().window().maximize()  

I have added this and am trying to run the following steps:

require 'rubygems'  require 'selenium-webdriver'    Given(/^User can set the enqury type to "([^"]*)"$/) do |enquiry_Type|    if driver.find_element(:id, 'select').displayed?      options = driver.find_elements(:tag_name, 'option')      options.each do |selectOption|        if(selectOption.text == enquiry_Type)          selectOption.click          break        end      end    end  end  

When I try to run the code I get the following error:

NameError: undefined local variable or method `driver' for #<Object:0x26f65f8>    ./features/step_definitions/Contact_Us_Steps.rb:5:in `/^User can set the enqury type to "([^"]*)"$/'     ./features/Contact_Us.feature:6:in `Given User can set the enqury type to "New Enquiry"'  

How do I link back to the ENV.rb file to be able to use the method. I want to use the method as it means I can set the Browser in a single place rather than in EVERY steps file.

Thanks and sorry for my noob question

Bootstrap modal wont submit unless refresh using modal.js rails

Posted: 07 Nov 2016 05:03 AM PST

Rails submit wont work unless I refresh the page.. don't know why that happens but i'm using the modal.js from bootstrap. I have added a button that when clicked would show a modal.. the problem i'm having is that when the modal pops up it shows the form but when I try to submit, it just doesn't work unless I refresh the page then the submit works.

<button type="button" class="btn btn-info glyphicon glyphicon-plus" data-toggle="modal" data-target="#myModal" style="margin-top:5px"> </button>  <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">  <div class="modal-dialog">    <div class="modal-content">        <div class="modal-header">        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>        <h4 class="modal-title" id="myModalLabel">Add Customer</h4>      </div>      <div class="container">        <%= form_for(@customer) do |f| %>        <div class="form-group row" style="margin-top:10px">          <%= f.label :first_name, class: "col-xs-2 col-form-label" %>          <div class="col-xs-3">            <%= f.text_field :first_name, class: "form-control" %>          </div>        </div>          <div class="form-group row">          <%= f.label :last_name, class: "col-xs-2 col-form-label" %>          <div class="col-xs-3">            <%= f.text_field :last_name, class: "form-control" %>          </div>        </div>          <div class="form-group row">          <%= f.label :phone_number, class: "col-xs-2 col-form-label" %>          <div class="col-xs-3">            <%= f.text_field :phone_number, class: "form-control" %>          </div>        </div>          <div class="form-group row">          <%= f.label :sex, class: "col-xs-2 col-form-label" %>          <div class="col-xs-3">            <%= f.select :sex, {'m' => "male", 'f' => "female"}%>          </div>        </div>                  </div>      <div class="modal-footer">        <%= f.submit "Submit", class: "btn btn-primary" %>      </div>      <% end %>    </div>  </div>  </div>  

Rails admin with current auth system

Posted: 07 Nov 2016 04:54 AM PST

we have a webpage www.example.com and we would like to create admin page for that website. We created link as www.example.com/admin but it uses current auth system.

After login to admin panel when user types www.example.com it does not ask for auth again. We are using rails. What is the best way to handle admin panel with current auth system?

syntax error, unexpected end-of-input [on hold]

Posted: 07 Nov 2016 06:12 AM PST

    class PinsController < ApplicationController    before_action :set_pin, only: [:show, :edit, :update, :destroy]        def index      @pins = Pin.all    end        def show    end        def new      @pin = Pin.new    end        def edit    end      def create      @pin = Pin.new(pin_params)        respond_to do |format|        if @pin.save          redirect_to @pin, notice: 'Pin was successfully created.' }        else          render action: 'new'        end      end        def update        if @pin.update(pin_params)          redirect_to @pin, notice: 'Pin was successfully updated.'        else          render action: 'edit'        end      end          def destroy      @pin.destroy      redirect_to pins_url    end    private      # Use callbacks to share common setup or constraints between actions.      def set_pin        @pin = Pin.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def pin_params        params.require(:pin).permit(:description)      end  end  

I know I am missing OR need to add a couple of 'ends'. However, I am just not sure where. Thank you :) I would really appreciate someone helping me to see where I have gone wrong. I am fairly new to ruby on rails.

Confused by rspec feedback from assert_select test

Posted: 07 Nov 2016 06:26 AM PST

I'm just getting going with rails and have a test for the index page for my Plants model:

The rspec test fails with this message:

$ rspec spec/views/plants/index.html.haml_spec.rb  Failures:      1) plants/index renders a list of plants       Failure/Error: assert_select "tr>td", :text => plant.height, :count => 2         Minitest::Assertion:         <48> expected but was         <Rose Mallow>..         Expected: 2           Actual: 0       # /Users/username/.rvm/gems/ruby-2.2.5/gems/minitest-5.9.1/lib/minitest/assertions.rb:139:in `assert'       # /Users/username/.rvm/gems/ruby-2.2.5/gems/minitest-5.9.1/lib/minitest/assertions.rb:174:in `assert_equal'       # /Users/username/.rvm/gems/ruby-2.2.5/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:278:in `assert_size_match!'       # /Users/username/.rvm/gems/ruby-2.2.5/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:175:in `block in assert_select'       # /Users/username/.rvm/gems/ruby-2.2.5/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:174:in `tap'       # /Users/username/.rvm/gems/ruby-2.2.5/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:174:in `assert_select'       # ./spec/views/plants/index.html.haml_spec.rb:15:in `block (2 levels) in <top (required)>'    Finished in 0.19797 seconds (files took 3.07 seconds to load)  1 example, 1 failure    Failed examples:    rspec ./spec/views/plants/index.html.haml_spec.rb:9 # plants/index renders a list of plants  

I guess I have two questions:

  1. Why is it looking for <48>? Are the lt/gt symbols just wrapping the string it is looking for (which seems a poor delimiter choice), or is it really expecting an html element named "48"?
  2. And more importantly, why can't it find the two instances of the height? When I do put render in the test I see exactly two instances rendered:

rendered test markup:

<h1>Listing plants</h1>  <table>  <thead>  <tr>  <th>Name</th>  <th>Scientific name</th>  <th>Height</th>  <th>Width</th>  <th>Spacing</th>  <th>Life cycle</th>  <th>Sun</th>  <th>Sow method</th>  <th>Direct seed start</th>  <th>Direct seed stop</th>  <th>Indoor seed start</th>  <th>Indoor seed stop</th>  <th>Transplant start</th>  <th>Transplant stop</th>  <th>Garden</th>  <th></th>  <th></th>  <th></th>  </tr>  </thead>  <tbody>  <tr>  <td>Rose Mallow</td>  <td>Lavatera trimestris</td>  <td>48</td>  <td>18</td>  <td></td>  <td>annual</td>  <td>full_sun</td>  <td>direct</td>  <td></td>  <td></td>  <td></td>  <td></td>  <td></td>  <td></td>  <td>Default Test Garden</td>  <td><a href="/plants/1">Show</a></td>  <td><a href="/plants/1/edit">Edit</a></td>  <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/plants/1">Destroy</a></td>  </tr>  <tr>  <td>Rose Mallow</td>  <td>Lavatera trimestris</td>  <td>48</td>  <td>18</td>  <td></td>  <td>annual</td>  <td>full_sun</td>  <td>direct</td>  <td></td>  <td></td>  <td></td>  <td></td>  <td></td>  <td></td>  <td>Default Test Garden</td>  <td><a href="/plants/1">Show</a></td>  <td><a href="/plants/1/edit">Edit</a></td>  <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/plants/1">Destroy</a></td>  </tr>  </tbody>  </table>  <br>  <a href="/plants/new">New Plant</a>  

Here's the test: spec/views/plants/index.html.haml_spec.rb

require 'rails_helper'    RSpec.describe "plants/index", type: :view do    before(:each) do      plant = FactoryGirl.create(:plant_rose_mallow)      assign(:plants, [ plant, plant ])    end      it "renders a list of plants" do      render      plant = FactoryGirl.create(:plant_rose_mallow)      puts plant.inspect      assert_select "tr>td", :text => plant.name, :count => 2      assert_select "tr>td", :text => plant.scientific_name, :count => 2      assert_select "tr>td", :text => plant.height, :count => 2      assert_select "tr>td", :text => plant.life_cycle, :count => 2      assert_select "tr>td", :text => plant.sun, :count => 2      assert_select "tr>td", :text => plant.sow_method, :count => 2    end  end  

Here's my factory: spec/factories/plants.rb

FactoryGirl.define do    factory :plant do      association :garden, :factory => :garden        factory :plant_rose_mallow do        name "Rose Mallow"         scientific_name "Lavatera trimestris"        height 48        width 18        life_cycle :annual        sun :full_sun        sow_method :direct      end    end  end  

Rails CORS error

Posted: 07 Nov 2016 04:12 AM PST

I have a Rails app with the following controller:

class Website::LeadsController < ApplicationController    before_action :cors_allow_all      def create      ...    end      ...      def cors_allow_all      headers['Access-Control-Allow-Origin'] = '*'      headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'      headers['Access-Control-Request-Method'] = '*'      headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'    end  

This controller is being reached from application in another domain like this:

  $.post('//subdomain.domain.com/route/to/controller/action', data);  

But I get

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://subdomain.domain.com/route/to/controller/action. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I am wondering why this might happen. One of possible suspects is Cloudflare, which I use as DNS and HTTP proxy.

Advice and comments are greatly appreciated.

MongoID chaining and scopes

Posted: 07 Nov 2016 06:47 AM PST

I use MongoID throughout my Rails project. I basically had a query like

def available_skus    skus.is_active.in_stock.order_by({:discount => :desc}, {:quantity => :desc})  end  

It refers partially to the scope inside my Sku model which's an embedded collection.

I've the following scopes in there

scope :is_active, -> { where(:status => true) }  scope :in_stock,  -> { any_of({:unlimited => true}, {:quantity.gt => 0}) }  scope :can_buy,   -> { is_active.in_stock }  

I created can_buy to avoid repetition since I use is_active.in_stock together very often and it has a specific meaning ; you can buy this sku.

In short, if I write skus.is_active.in_stock it works perfectly and get some results, but if I use skus.can_buy then it gives no result.

I don't understand the behaviour here. Isn't can_buy a simple shortcut to the two other scopes ?

What is best practice for using decorators in a rails app

Posted: 07 Nov 2016 04:14 AM PST

In my rails app there is a reporting page with a lot of stats and a lot of charts, there are over 40 values and over 12 charts to give an idea.

There is a lot of data to manipulate so I started moving that code out to decorators, but I'm not sure this is the best way as my controller now looks like shit.

I'm having trouble tracking code - what has been tested, what is working, what is redundant, so maintability already sucks a bit.

Can anyone offer advice or suggest a pragmatic solution/methodology for keeping my project from turning into an absolute mess? Is there something I'm doing fundamentally wrong regarding my method or process, or a gap in my knowledge of Ruby/Rails that can be discerned from my example code below and should be done in another way?

Here's an example of my base decorator class, a decorator and my controller:

Base decorator:

module Insights    class InsightDecorator      attr_reader :insight        def initialize(insight)        @insight = insight      end        def method_missing(method_name, *args, &block)        insight.send(method_name, *args, &block)      end        def respond_to_missing?(method_name, include_private = false)        insight.respond_to?(method_name, include_private) || super      end    end  end   

One of 14 decorators:

module Insights    class FanAdds < InsightDecorator      def previous        FanAdds.new(Insight.previous page_id, insight_end)      end        def get_likes_increase        previous.insight.is_a?(Insight) ? (get_monthly_total - previous.get_monthly_total).to_i : 0      end        def get_daily_total        begin          get_insight_by_title('Daily New Likes')['values']        rescue          logger.error 'No daily new likes found'          nil        end      end        def get_monthly_total        get_daily_adds.inject(0) {|total, fan| total + fan['value'] }      end    end  end  

Show method in insight contoller (is looking way bad! Is there a better way to fix this?!?)

def show    @insight_page_impressions_gender = Insights::PageImpressionsGender.new(@insight)    @insight_page_monthly            = Insights::PageMonthly.new(@insight)    @insight_page_stories            = Insights::PageStories.new(@insight)    @insight_engagement_day_of_week  = Insights::EngagementDayOfWeek.new(@insight)        @insight_charts_fan_growth       = Insights::Charts::FanGrowth.new(@insight)    @insight_charts_impressions      = Insights::Charts::PageImpressions.new(@insight)    @paid_organic_viral_impressions  = Insights::Charts::PaidOrganicViralImpressions.new(@insight)    @story_type                      = Insights::Charts::StoryTypesOfImpressions.new(@insight)    @age_gender_impressions          = Insights::Charts::AgeGenderOfImpressions.new(@insight)    @insight_charts_stories          = Insights::Charts::Stories.new(@insight)    # ... and so on    @fan_adds                        = Insights::FanAdds.new(@insight)  end  

validates_uniqueness_of with a datetime

Posted: 07 Nov 2016 05:40 AM PST

I seem to encounter this problem from time to time when I want to validate a field and scope it to a particular date when I am storing datetime.

validates_uniqueness_of :user_id, scope: [:starts_at, :state]  

The problem is starts_at is stored as datetime but I don't want to validate the exact time but rather the general date.

When I encounter this problem I usually create a custom validation method, and sometimes that makes sense when there's a window of time, but I'm wondering if I'm overlooking a better solution when I only care about the entire date.

I would like to avoid creating custom validation like the one below if there's another possibility.

Old way

def check_user_uniqueness    if EventLog.where("start_at::date = ? AND id <> ? AND user_id = ?",      start_at.to_date, id, user_id).count > 0      errors.add(:user_id, "isn't available on this date")    end  end  

Thanks

Rails describe HTML content source

Posted: 07 Nov 2016 03:50 AM PST

I am looking for a gem or elegant way to setup system where I would be able to see where certain HTML content came from. I am working on a big project, and a lot of my times goes determining where a certain piece of HTML content came from. I know you are able to see which layouts, partials are used to render a page in logs but I am looking for something more practical.

An example of this would be.

<!-- ... app/views/layouts/main.html.slim -->  <body>    <!-- ... app/views/people/index.html.slim -->    <div class="foo">      <table clas="items">        <!-- ... app/views/people/shared/_person.html.slim -->        <td>          <span>John Doe</span>        </td>      </table>    </div>  </body>  

Where before rendering any partial / page / layout rails render engine would add a comment describing origin.

No comments:

Post a Comment