Thursday, November 24, 2016

Rails/Simpleform: Set an image as input instead of upload | Fixed issues

Rails/Simpleform: Set an image as input instead of upload | Fixed issues


Rails/Simpleform: Set an image as input instead of upload

Posted: 24 Nov 2016 08:06 AM PST

I have an Instagram clone app where users can upload an image with a caption. I want to an input so that the user can either upload an image or search for an image and choose one.

The search functionality has been implemented so now there are 6 images in the '/assets/images' folder that should be displayed to the user(No hotlinking so the images had to be downloaded). When clicked the image should be added the the @post variable as f.input :image. How would I go about accomplishing this?

*post_controller.rb*  @post = current_user.posts.build    *new.html.haml*  = form_image_select(@post)    = simple_form_for @post, html: { multipart: true } do      ...      /Upload image      = f.input :image, label: false, input_html: { onChange: 'loadFile(event)' }      ...      /One of the following images should be somehow selected into f.input      - @imgPaths.each do |x|        = image_tag x, width: '200'  

Cheers!

Rails 4 How to assign value to dropdowns in a hash?

Posted: 24 Nov 2016 08:03 AM PST

For example I need to create a dropdown with options "Sedentary", "Lightly Active", "Active", "Very Active" and assign those to a user as an integer(0, 1,..3). How can I make a hash

activity_level = {"Sedentary" => 0,                    ..............,                    "Very Active" => 3}  

and store an integer value instead of a string?

Testing password update - Rspec, Capybara, Devise

Posted: 24 Nov 2016 07:51 AM PST

I'm pretty new to ROR and testing and i'm trying to test a password update to a RegistrationsController inherited from DeviseRegistrationsController.

I included at the end of my controller an update_resource method, showed here

My controller

class Users::RegistrationsController < Devise::RegistrationsController     ...     def update_resource(resource, params)     if params[:password].blank? && params[:password_confirmation].blank?       resource.update_without_password(params)     else       super     end   end    end  

My controller test file

require "rails_helper"    RSpec.describe Users::RegistrationsController, type: :controller do      describe "update password" do      before do        @request.env['devise.mapping'] = Devise.mappings[:user]      end      let(:user){ FactoryGirl.create(:user, password: 'current_password', password_confirmation: 'current_password') }        context "with a valid password parameter" do        it "updates user in the database" do            put :update, params: { id: user, user: FactoryGirl.attributes_for(:user, password: '12', password_confirmation: '12') }          user.reload            expect(user.password).to eq("newpassword12")        end      end    end    end  

I'm receiving the follow error

 2) Users::RegistrationsController update password with a valid password parameter updates user in the database   Failure/Error: expect(user.password).to eq("newpassword12")       expected: "newpassword12"          got: "current_password"       (compared using ==)   # ./spec/controller/users/registrations_controller_spec.rb:75:in `block (4 levels) in <top (required)>'  

Any idea what am i doing wrong?

Capybara-webkit: Tests got stuck while running all together

Posted: 24 Nov 2016 07:30 AM PST

I have experienced a strange behavior while trying to run my tests with capybara-webkit. I am trying to run a feature file which have scenario outline with 3 examples. If I run these examples separately then all are passing but if I try to run them all together then it just got stuck at some point. It does not fail either. It just kept running(have even waited for half an hour as well when it is suppose to take about 1 minute).

Also want to mention that I have run the feature by using selenium driver and it runs without any problem. Any idea what is the problem with running all the tests together while using capybara-webkit?

PS: This is my first time trying to run tests with webkit so probably missing something very basic thing so please suggest and excuse me in case I am missing something very basic.

Rails form for nested attributes needs to discard build if rejected

Posted: 24 Nov 2016 07:42 AM PST

I#m having trouble with a form that also handles nested attributes. The parent model "meeting" accepts nested attributes for the child model "invitation". Note it is only possible to send one invitation for a meeting, but it is optional.

The model for Meeting includes:

  has_one :invitation, :dependent => :destroy    accepts_nested_attributes_for :invitation, :reject_if => proc { |a| a[:user_id].blank?  }, :allow_destroy => true  

The problem is in the view views/meetings/_form.html.erb. I try to handle all attributes for meeting and invitation for the views new, show and edit. Because I want a user to be able to add an invitation when there hasnt been one previously I put

<%= f.fields_for :invitation, @meeting.invitation ||= @meeting.build_invitation do |ff| %>  

But this gives me an error when I want to edit the meeting and the invitation was blank (so it was rejected) "Failed to save the new associated invitation."

What am I doing wrong?

Javascript in HAML in Javascript

Posted: 24 Nov 2016 07:50 AM PST

I've got a question that mightve been asked before but i have trouble finding a proper description. I hope someone can help me out.

In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. How do I do this in embedded rails in javascript?

 :javascript      $('#accu').change(function() {        var accu_id = $("#accu")[0].selectedOptions[0].value        var price = "#{currency(Product.find_by(id: accu_id).price2)}"        $('#price_accu').append(price)      });  

Or is there an easier way to do this?

Rails 4 - ActionController can't require 2 keys

Posted: 24 Nov 2016 08:04 AM PST

Looking at the documentation for ActionController::Parameters for the require method I read the followiing

When given an array of keys, the method tries to require each one of them in order. If it succeeds, an array with the respective return values is returned:

params = ActionController::Parameters.new(user: { ... }, profile: { ... })  user_params, profile_params = params.require(:user, :profile)  

but when I run this code with rails console, my output is very different

[70] pry(main)> params = ActionController::Parameters.new(user: { a: 1 }, profile: { b: 2 })  => {"user"=>{"a"=>1}, "profile"=>{"b"=>2}}  [71] pry(main)> user_params, profile_params = params.require(:user, :profile)  ArgumentError: wrong number of arguments (2 for 1)  from /home/myuser/.rbenv/versions/2.1.6/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_controller/metal/strong_parameters.rb:244:in `require'  

When I read when given an array of keys and saw the example, I thought that maybe they made a mistake when writing the example, so I tried this as well, but it did not work either.

[72] pry(main)> user_params, profile_params = params.require([:user, :profile])  ActionController::ParameterMissing: param is missing or the value is empty: [:user, :profile]  from /home/myuser/.rbenv/versions/2.1.6/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_controller/metal/strong_parameters.rb:249:in `require'  

What is going on here?

undefined method `aasm_state' for nil:NilClass

Posted: 24 Nov 2016 06:47 AM PST

When I make a shopping website,I find a bug that I can't solve.I have a page to show all orders,and it can change the state of orders.When I go to that page,it will give me the following error:

undefined method `aasm_state' for nil:NilClass

But,in rails console I can find the state of the order.Can you help me to solve this?If you want more details,please let me know.Thank you very much~

I'm so sorry that I don't have enough reputation to post images. SO I paste the code from rails console in the comment.

How to DRY has_attached_file that I write in 5 models

Posted: 24 Nov 2016 06:54 AM PST

This is my code that I write in 5 different models (same code).

has_attached_file :image,      s3_region: 'ap-northeast-1',      storage: :s3,      s3_protocol: :https,      s3_credentials:  "#{Rails.root}/config/amazon_s3.yml",      url: ':s3_domain_url',      path:  '/images/:id/:filename',      s3_host_alias: 'https://s3-ap-northeast-1.amazonaws.com/'  

Is there any way to DRY it out so that I have it only in one place and use it in different models?

mongoid force save full document to database

Posted: 24 Nov 2016 06:41 AM PST

Decided to use mondgo to cache some data from external system. At the moment app cares about only some of the fields but I;d like to put into mongo the full document received from the other system in case something is needed later. I do like this:

resource.attributes.merge! updated_doc  resource.save!  

But resource is not saved because mongoid doesn't recognize the document has been updated. attribute_will_change! does not help even for attributes defined in the model. Even if I do some attribute dirty like resource.some_attr = "something", save would update only this attribute and nothing else.

So looking for a way to update the whole document into mongo. But can't find anything.

I'm about to try Mongoid::Attributes::Dynamic. But I wanted to avoid it and only update unknown attributes when I know this is safe.

Generate marker with rails, ajax and Mapbox

Posted: 24 Nov 2016 06:49 AM PST

I want my users be able to generate markers on their own maps (on their profile page), when they create a post and enter a country. For now, I'm able to create a post, to choose a country, and save longitude and latitude using geocoder gem, but I am not able to generate the marker using ajax call, here is my codes :

users_controller.rb (show method):

 def show       @post_all = @user.posts        @geojson = Array.new()        @post_all.each do |pos|          @geojson << {            type: 'Feature',            geometry: {              type: 'Point',              coordinates: [pos.longitude, pos.latitude]            },            properties: {              name: pos.title,              address: pos.country,              :'marker-color' => '#d9534f',              :'marker-symbol' => 'circle',              :'marker-size' => 'medium'            }          }        end        respond_to do |format|          format.html          format.json { render json: @geojson }  # respond with the created JSON object        end    end   

my application.js file :

$(document).ready(function(){    L.mapbox.accessToken = "pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw";    var map = L.mapbox.map('map').setView([48.856614, 2.3522219000000177], 4);    var style = L.mapbox.styleLayer("mapbox://styles/antoto/civn0z51d00002ko4tmlch2zn").addTo(map);    var marker = L.marker([48.856614, 2.3522219000000177], {        icon: L.mapbox.marker.icon({          'marker-color': '#d9534f'        })      })      .bindPopup('hello')      .addTo(map);    map.scrollWheelZoom.disable();      $.ajax({      dataType: 'json',      url: '/#{:id}/show.json',      success: function(data) {        geojson = $.parseJSON(data)        console.log(data)        map.featureLayer.setGeoJSON(geojson)      },      error: function(data) {        console.log(data + ' error')      }    });   });  

I think that there are problems in my URL in the ajax call, but when a create the geojson I don't know what url to use.

Change requesting format

Posted: 24 Nov 2016 06:33 AM PST

That`s my carts_controller.rb. By default controllers action add renders add.js.erb in /app/views/carts/

class CartsController < ApplicationController    def add      find_cart_and_product      @cart.products << @product      CartMailer.product_added(@product).deliver_now    end  end  

and my test

describe 'POST #add' do    let(:cart_full_of){ create(:cart_with_products) }    let(:product){ create(:product) }    before do      post :add, session: { cart_id: cart_full_of.id }, params: { product_id: product.id}    end    it { expect(response.status).to eq(200) }    it { expect(response.headers["Content-Type"]).to eql("application/javascript"; charset=utf-8")}    it { is_expected.to render_template :add }    it 'should add current product into cart' do      expect(cart_full_of.products).to eq([product])    end  end  

has failed with common error for all test items:

 Failure/Error: post :add, session: { cart_id: cart_full_of.id }, params: { product_id: product.id}     ActionController::UnknownFormat:     CartsController#add is missing a template for this request format and variant.       request.formats: ["text/html"]     request.variant: []  

I think problem with expected requesting format,so how to force tests render with request.formats: ["application/javascript"] instead ["text/html"]?

Testing devise custom session controller with rspec

Posted: 24 Nov 2016 06:18 AM PST

I'm having custom controller

class Users::SessionsController < Devise::SessionsController    # POST /resource/sign_in    def create      binding.pry      super    end  end  

routes added

devise_for :users, controllers: { sessions: "users/sessions" }  

and it works during signin using browser. But inside controller test breakpoint inside create is not being hit:

RSpec.describe Users::SessionsController, type: :controller do      describe 'POST #create' do        context 'pending activation user with expired password' do        it 'could not login' do          user = create :operator_user, status: User.statuses[:activation_pending], password_changed_at: (1.day + 1.second).ago          @request.env['devise.mapping'] = Devise.mappings[:user]          sign_in user            user.reload          expect(user).to be_locked        end      end    end    end    RSpec.configure do |config|    #...    # Devise methods    config.include Devise::TestHelpers, type: :controller    # ...  end  

I expect expression sign_in user to fall into create method that I've overrided. What am I doing wrong?

ps: it even falls into standard devise SessionsController#create

Monthly Total Calculation Using Ruby Calculations

Posted: 24 Nov 2016 06:20 AM PST

I have the calculations to tabulate the totals since the beginning of this app. I need help calculating the totals for just the current month and am not sure how to do that. Thanks in advance.

item.rb

class Item < ActiveRecord::Base    def profit_calc      sold_for - bought_for - fees - shipping rescue 0    end      def self.purchase_total      sum(:bought_for)    end      def self.fee_total      sum(:fees)    end      def self.shipping_total      sum(:shipping)    end      def self.sales_total      sum(:sold_for)    end      def self.profit_total      sold.sum(:sold_for) - sold.sum(:bought_for) - sold.sum(:fees) -    sold.sum(:shipping)    end      def profit_margin_item      profit_calc / sold_for * 100 rescue 0    end      def self.profit_margin_total      profit_total/ sum(:sold_for) * 100    end      scope :visible, -> { where(sold: false) }    scope :sold, -> { where(sold: true) }      def self.search(search)      where("description LIKE ?", "%#{search}%")    end  end  

statistics.html.erb

<h1 id="title">Statistics</h1>  <br>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Bought</th>        <th>Bought This Month</th>        <th>Total Sold</th>        <th>Sold This Month</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= @items.count %></td>        <td><%= @items_month.count %></td>        <td><%= @items_sold.count %></td>        <td><%= @items_sold_month.count %></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Purchases</th>        <th>Total Month Purchases</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_currency(@items.purchase_total) %></td>        <td></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Sales</th>        <th>Total Month Sales</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_currency(@items.sales_total) %></td>        <td></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Fees</th>        <th>Total Month Fees</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_currency(@items.fee_total) %></td>        <td></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Shipping</th>        <th>Total Month Shipping</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_currency(@items.shipping_total) %></td>        <td></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Profit</th>        <th>Total Month Profit</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_currency(@items.profit_total) %></td>        <td></td>      </tr>    </tbody>  </table>    <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total Margin</th>        <th>Total Month Margin</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_to_percentage(@items.profit_margin_total, precision: 0) %></td>        <td></td>      </tr>    </tbody>  </table>  

dependent: :destroy not working with validates_associated

Posted: 24 Nov 2016 07:08 AM PST

I've been working with two models and form validations on nested attributes with uniquness.

When saving the form, the uniqueness validation is scoped to the the email address of the list user. I encountered a bug where if the user tried to save two emails in the one transaction the validation is not fired because it checks against existing records in the database, rather than objects in memory which are about to be saved.

My models are as follows:

class List < ActiveRecord::Base      has_many :competitors, dependent: :destroy, inverse_of: :list    accepts_nested_attributes_for :competitors, reject_if: :all_blank, allow_destroy: true    end      class Competitor < ActiveRecord::Base      belongs_to :list, inverse_of: :competitors      validates :list, presence: true    validates :name, presence: true, length: { minimum: 2, maximum: 20 }    validates :email, presence: true, format: { with: User::EMAIL_REGEX }    validates :email, uniqueness: { scope: :list_id }    end  

To fix this, I added:

validates_associated :competitors  

to my list model which now causes the form to behave as expected with the validation firing off when the user tries to save two email addresses for competitors which are the same.

However, running my tests, I found that the example in this block is now causing a failure.

describe "@competitors" do    let!(:list) { FactoryGirl.create(:list) }    let!(:competitor) { FactoryGirl.create(:competitor, list_id: list.id) }      it "deletes associated competitors if the list is deleted" do      expect { list.destroy }.to change { Competitor.count }.by(-1)    end  end  

My research so far tells me that this is not a common problem, so I think I'm doing something wrong, but I can't quite tell what that is.

I'm using ruby 2.3.0 and rails 4.2.7.1

Validate associated object (lazy validation)

Posted: 24 Nov 2016 07:54 AM PST

I'm trying to solve validation of associated object with condition.

User doesn't need to have filled author_bio until he is author. So app needs to ensure, that author can't create post without author_bio and author_bio can't be deleted if user already created any post.

class User < ApplicationRecord    has_many :posts, foreign_key: 'author_id', inverse_of: :author      validates :author_bio, presence: { if: :author? }      def author?      posts.any?    end   end    class Post < ApplicationRecord    belongs_to :author, class_name: 'User', inverse_of: :posts, required: true  end  

Unfortunately this doesn't validate author on creation of new post:

user = User.first  user.author_bio  => nil    post = Post.new(author: user)  post.valid?  => true  post.save  => true  post.save  => false  post.valid?  => false  

So how can I prevent creating of new post by user without author_bio? I can add second validation to Post model, but this is not DRY. Is there any better solution?

Rails has_one with conditional foreign key

Posted: 24 Nov 2016 05:46 AM PST

I am currently implementing the database structure to account for firewall Access Control Lists. It is required to have for each Interface on a Router the possibility to define up to two AccessListables, one for WAY_IN and one for WAY_OUT. To make things more complicated, AccessListable, as the name implies, is polymorphic and can be either an AccessList or an AccessListReference. Each AccessListable can only be referenced to a single Interface at a time and is constrained to be used for the way specified in the AccessList's eponymic attribute.

As can be seen below, each AccessListable however has two relations to Interface of which one is obsolete, since it can only be used for the corresponding way. An AccessListReference does not have a way attribute, but must instead use the one given by its corresponding AccessList.

class Interface < ActiveRecord::Base    belongs_to :router    belongs_to :access_listable_in,  foreign_key: 'access_listable_in_id',  validate: true, polymorphic: true    belongs_to :access_listable_out, foreign_key: 'access_listable_out_id', validate: true, polymorphic: true  end    class AccessList < ActiveRecord::Base    #DB-attribute way is element of { WAY_IN, WAY_OUT }    has_one :interface_in,  class_name: Interface.name, foreign_key: 'access_listable_in_id',  as: :access_listable_in    has_one :interface_out, class_name. Interface.name, foreign_key: 'access_listable_out_id', as: :access_listable_out  end    # can be thought of as a symlink with a custom name like  # CUSTOM_NAME => AccessList  class AccessListReference < ActiveRecord::Base    belongs_to :access_list    has_one :interface_in,  class_name: Interface.name, foreign_key: 'access_listable_in_id',  as: :access_listable_in    has_one :interface_out, class_name. Interface.name, foreign_key: 'access_listable_out_id', as: :access_listable_out  end  

The obvious solution to this is creating a method in each AccessListable that chooses which relation to pick based on its way like this

def interface    return case self.way #for AccessListReference, it's self.access_list.way      when WAY_IN  then self.interface_in      when WAY_OUT then self.interface_out      else raise "invalid way #{self.way}"      end  end  

Doing this, however, prevents me from eager loading in an efficient way, because in order to get the Router that corresponds to an AccessList I have to go through both relations and use this abomination, which produces 5 queries in total, when only 3 are actually needed

AccessList.includes(interface_in: :router, interface_out: :router).all()  

The goal here is to find a way to make the following work

AccessList.includes(interface: :router).all()  

Is there a way to do it? I have thought about using STI in order to split the AccessList into types AccessListIn and AccessListOut, since they share the same attributes, but I have a feeling this just adds unnecessary complexity, since I would in that case have to make AccessListReferenceIn and AccessListReferenceOut as well.

Also, in most other scenarios I'm only interested in the AccessListable as such, and not so much about the way it was defined for. Any tips on how to solve this in the best way are greatly appreciated.

Allow Input Field Array as Params in Rails

Posted: 24 Nov 2016 05:40 AM PST

I have a form that I submit to my Rails application.

My field names are

<input name="custom[x]">  <input name="custom[y]">  <input name="custom[z]">  

These are custom fields so the names can change. Now I want to get the entire custom array in my Rails app.

I tried:

def form_params     params.permit(:custom)  end  

This does not work and returns always NULL.

What do I have to change?

Afterwards I would like to convert the while custom array into a JSON object.

Rails chartkick how to add names

Posted: 24 Nov 2016 05:09 AM PST

I am using gem 'chartkick' and have such code:

        <%= pie_chart question.responses.group(:answer_variant_id).count %>  

the table responses is connected with table answer_variants through answer_variant_id. Currently my pie chart shows answer variant ids, but how could I make it displaying answer_variant.title?

Thanks

Invoke DB2 encrypt function in Active Record in Ruby on Rails for new record

Posted: 24 Nov 2016 06:48 AM PST

I want to encrypt a value using the IBM DB2 encrypt built-in function. I am using the below code for saving a record.

````  user = User.new   user.password = "encrypt('mysecurepassword')"   user.save  ````  

Active Record is saving the password as a string and I am unable to call the DB2 encrypt function.

Rails/Rspec specific test case under 'development' environment for workaround

Posted: 24 Nov 2016 06:15 AM PST

I normally run RSpec with test environment with CircleCI.

Is there any way to run specific test case under development environment for workaround.

P.S. I found some issue on rails-spec which acting up under test environment.

CookieOverflow on Rails 4 API application

Posted: 24 Nov 2016 04:57 AM PST

I'm developing a Rails app (API) using the devise_token_auth gem. I'm trying to implement the "Reset Password" feature and I'm running into some troubles.

I am supposed to make a PUT request to the server application with 3 custom headers (uid, access-token and client) but when I do this:

http = Net::HTTP.new("127.0.0.1", "3000")  request = Net::HTTP::Put.new("/api/v1/auth/password")    request['Uid'] = @@sens_pms["uid"]  request['Access-Token'] = @@sens_pms["token"]  request['Client'] = @@sens_pms["client_id"]    response = http.request(request)  

It throws this error:

ActionDispatch::Cookies::CookieOverflow (ActionDispatch::Cookies::CookieOverflow)  

Why? What can I do to solve this?

Shall I commit solr file?

Posted: 24 Nov 2016 07:16 AM PST

I have added the full text search by sunspot gem and apache solr. I got many new files in my project. I don't know, is it right, but I commited this files:

solr/configsets/sunspot/conf/_rest_managed.json   solr/configsets/sunspot/conf/admin-extra.html   solr/configsets/sunspot/conf/currency.xml   solr/configsets/sunspot/conf/elevate.xml   solr/configsets/sunspot/conf/lang/stopwords_en.txt   solr/configsets/sunspot/conf/mapping-ISOLatin1Accent.txt   solr/configsets/sunspot/conf/protwords.txt   solr/configsets/sunspot/conf/schema.xml   solr/configsets/sunspot/conf/scripts.conf   solr/configsets/sunspot/conf/solrconfig.xml   solr/configsets/sunspot/conf/spellings.txt   solr/configsets/sunspot/conf/synonyms.txt   solr/default/core.properties   solr/default/data/index/segments_1  solr/default/data/index/write.lock   solr/development/core.properties   solr/development/data/index/segments_1  solr/development/data/index/write.lock   solr/pids/development/sunspot-solr-development.pid   solr/solr.xml   solr/test/core.properties   solr/test/data/index/segments_1  solr/test/data/index/write.lock   

After this commit I have got files:

new file:   solr/development/data/index/_1.fdt      new file:   solr/development/data/index/_1.fdx      new file:   solr/development/data/index/_1.fnm      new file:   solr/development/data/index/_1.nvd      new file:   solr/development/data/index/_1.nvm      new file:   solr/development/data/index/_1.si      new file:   solr/development/data/index/_1_1.liv      new file:   solr/development/data/index/_1_Lucene50_0.doc      new file:   solr/development/data/index/_1_Lucene50_0.pos      new file:   solr/development/data/index/_1_Lucene50_0.tim      new file:   solr/development/data/index/_1_Lucene50_0.tip      new file:   solr/development/data/index/_2.fdt      new file:   solr/development/data/index/_2.fdx      new file:   solr/development/data/index/_2.fnm      new file:   solr/development/data/index/_2.nvd      new file:   solr/development/data/index/_2.nvm      new file:   solr/development/data/index/_2.si      new file:   solr/development/data/index/_2_Lucene50_0.doc      new file:   solr/development/data/index/_2_Lucene50_0.pos      new file:   solr/development/data/index/_2_Lucene50_0.tim      new file:   solr/development/data/index/_2_Lucene50_0.tip      new file:   solr/development/data/index/segments_5      new file:   solr/development/data/tlog/tlog.0000000000000000000      new file:   solr/development/data/tlog/tlog.0000000000000000001      new file:   solr/development/data/tlog/tlog.0000000000000000002      new file:   solr/development/data/tlog/tlog.0000000000000000003    Changes not staged for commit:    (use "git add/rm <file>..." to update what will be committed)    (use "git checkout -- <file>..." to discard changes in working directory)        modified:   app/controllers/posts_controller.rb      modified:   app/views/posts/index.html.erb      deleted:    solr/development/data/index/_2.fdt      deleted:    solr/development/data/index/_2.fdx      deleted:    solr/development/data/index/_2.fnm      deleted:    solr/development/data/index/_2.nvd      deleted:    solr/development/data/index/_2.nvm      deleted:    solr/development/data/index/_2.si      deleted:    solr/development/data/index/_2_Lucene50_0.doc      deleted:    solr/development/data/index/_2_Lucene50_0.pos      deleted:    solr/development/data/index/_2_Lucene50_0.tim      deleted:    solr/development/data/index/_2_Lucene50_0.tip      deleted:    solr/development/data/index/segments_1      deleted:    solr/development/data/index/segments_5    Untracked files:    (use "git add <file>..." to include in what will be committed)        solr/development/data/index/_4.fdt      solr/development/data/index/_4.fdx      solr/development/data/index/_4.fnm      solr/development/data/index/_4.nvd      solr/development/data/index/_4.nvm      solr/development/data/index/_4.si      solr/development/data/index/_4_Lucene50_0.doc      solr/development/data/index/_4_Lucene50_0.pos      solr/development/data/index/_4_Lucene50_0.tim      solr/development/data/index/_4_Lucene50_0.tip      solr/development/data/index/segments_9      solr/development/data/tlog/tlog.0000000000000000004      solr/development/data/tlog/tlog.0000000000000000005      solr/development/data/tlog/tlog.0000000000000000006      solr/development/data/tlog/tlog.0000000000000000007  

What files I need commit, add .gitignore, add to my projects?

Compare two fields in Rails ActiveRecord with aliases

Posted: 24 Nov 2016 05:30 AM PST

I have a DB with cryptic field names, so I have aliases for each of them:

alias_attribute :charge_duty, :aeaqst  .....  

The task is to compare two fields with normal names (aliases) not select the records when they are equal. Now, I do where('aaayva <> aaa0va'), what I have to change to use my aliases? I can do where.not(charge_duty: 'value'), but how to replace value with other field name?

How can I configure database.yml from an existing database on bluehost?

Posted: 24 Nov 2016 04:32 AM PST

I already have a database and a user/password that I create from cPanel "MySQL Wizard", but I'm having problems while configuring the database.yml file. I don't know how it should look like.

When I created my app on my computer to run on localhost:3000, only running the "rake db:create" command made everything works, but now that I have a database that was created before the app, I don't know how can I configure it.

I tried to read the some rubyonrails.org guides, but it didn't help me.

Does belongs_to creates an association in Rails 5?

Posted: 24 Nov 2016 06:34 AM PST

I have the following models:

class User    has_many :items  end    class Item    belongs_to :user  end  

Inside create_table for items I have:

t.belongs_to :person  

I'm using Rails 5 and I saw this automatically creates an index for person_id inside the items table. However, according to this SO thread, this isn't supposed to happen.

Are the answers incorrect or was this added into Rails 5 (or some Rails 4.x version)?

'dependent: :destroy' on 'has_many :through' with 'polymorphic: true'

Posted: 24 Nov 2016 04:23 AM PST

Can't get dependent: :destroy to work on association through a polymorphic association.

I have this associations on my model:

  has_many :playlist_items, -> { order(position: :asc) }, dependent: :destroy    has_many :media_files, through: :playlist_items, source: :content, source_type: 'MediaFile'    has_many :plugins, through: :playlist_items, source: :content, source_type: 'Plugin', dependent: :destroy  
  • I want related PlaylistItems to be destroyed
  • I want related Plugins through PlaylistItems to be destroyed
  • I want related MediaFiles through PlaylistItems to be retained

Maybe i should define destroy policy on PlaylistItem model, but i don't know how.

Thanks.

Failed test expectation

Posted: 24 Nov 2016 05:28 AM PST

I have a carts controller in my app

class CartsController < ApplicationController    def show      @cart = Cart.find(session[:cart_id])      @products = @cart.products    end  end  

and wrote test cartscontroller_spec.rb

RSpec.describe CartsController, type: :controller do    describe 'GET #show' do      let(:cart_full_of){ create(:cart_with_products, products_count: 3)}      before do        get :show      end      it { expect(response.status).to eq(200) }      it { expect(response.headers["Content-Type"]).to eql("text/html; charset=utf-8")}      it { is_expected.to render_template :show }      it 'should be products in current cart' do        expect(assigns(:products)).to eq(cart_full_of.products)      end    end  end  

My factories.rb looks such:

factory(:cart) do |f|    f.factory(:cart_with_products) do      transient do        products_count 5      end      after(:create) do |cart, evaluator|        create_list(:product, evaluator.products_count, carts: [cart])      end    end  end    factory(:product) do |f|    f.name('__product__')    f.description('__well-description__')    f.price(100500)  end   

but I have got an error:

FCartsController GET #show should be products in current cart  Failure/Error: expect(assigns(:products)).to eq(cart_full_of.products)       expected: #<ActiveRecord::Associations::CollectionProxy [#<Product id: 41, name: "MyProduct", description: "Pro...dDescription", price: 111.0, created_at: "2016-11-24 11:18:43", updated_at: "2016-11-24 11:18:43">]>          got: #<ActiveRecord::Associations::CollectionProxy []>  

Looks like I have no created products at all because of empty product model array ActiveRecord::Associations::CollectionProxy [], simultaneously, I investigate product`s id is increasing with every test attempt.At the moment I have no solid ideas that is wrong

unable to display ruby on rails app page in production environment in local machine

Posted: 24 Nov 2016 04:17 AM PST

I am using puma server in my rails5 application. my application consists of only one page which has google map. I have written all the scripts for maps in a file called home.coffee. when i run the same in development environment it runs fine but as soon as I start application in production mode it stops working. I have also made config.assets.compile = true in production.rb file and also done assets precompiled and starting server using command rails s -e production. any one help me out why it is not loading page. I am attaching up my files along with question,. if anybody can help me out, I would be great thank [Brower[while running on development mode][1\full.

enter image description here

production.rb

config.assets.compile = true  config.serve_static_assets = true  config.public_file_server.enabled = true  

application.js file

//= require jquery  //= require jquery_ujs  //= require underscore  //= require gmaps/google  //= require gmail_api  //= require home  //= require markerclusterer  //= require infobox  //= require turbolinks  // require_tree .  

Rails/Rspec JSON boolean being converted to strings when testing post call in test env

Posted: 24 Nov 2016 03:55 AM PST

I am testing a JSON request to our API, It will respond with JSON. It seems like all the boolean within the JSON get converted to strings as we post them the endpoint only under test environment.

However RAILS_ENV=development bundle exec guard works ok (no conversion), but once RAILS_ENV=test bundle exec guard converts all the boolean to string.

This is my test case using mock.

  it 'create proration item' do      # guess need to create a dummy account with stripe_customer_id      account = create(:account, stripe_customer_id: 'cus_00000000000000')      invoice = create(:invoice, stripe_invoice_id: 'in_00000000000000' )        # create a plan      plan = create(:plan)      stripe_helper.create_plan(id: plan.stripe_plan_id)        Stripe::InvoiceItem.create(        amount: 300,        currency: 'jpy',        description: "#{300} charged",        proration: true,        type: 'invoiceitem'      )      item_objs = Stripe::InvoiceItem.list(:limit => 10)        # create a event mock based on objs above      event = StripeMock.mock_webhook_event('invoice.payment_succeeded', {        id: invoice.stripe_invoice_id,        lines: item_objs,        customer: account.stripe_customer_id      })        # Mocking up private method :fetch_invoice_details      balance_txn = Stripe::BalanceTransaction.retrieve('txn_05RsQX2eZvKYlo2C0FRTGSSA')      allow_any_instance_of(InvoicePaymentSucceeded).to receive(:fetch_invoice_details).and_return(balance_txn)        # when it's false (This should be changed depending on cases). Here we don't test private method.      allow_any_instance_of(InvoicePaymentSucceeded).to receive(:initial_invoice?).and_return(false)        post '/stripe-events', event.as_json      expect(response.status).to eq 200    end  

Within end point handler, I could see the values.

Under test environment,

#<Stripe::Event:0x3fe2ea57e95c id=test_evt_2> JSON: {    "id": "test_evt_2",    "created": "1326853478",    "livemode": "false",    "type": "invoice.payment_succeeded",    "object": "event",    "data": {"object":{"id":"in_00000000000000","date":"1394018368","period_start":"1394018368","period_end":"1394018368","lines":{"object":"list","data":[{"id":"test_ii_1","object":"invoiceitem","date":"1349738920","amount":"300","livemode":"false","proration":"true","currency":"jpy","customer":"cus_test","description":"300 charged","invoice":null,"subscription":null,"type":"invoiceitem"}],"url":"/v1/hashs","has_more":"false"},"subtotal":"30000","total":"30000","customer":"cus_00000000000000","object":"invoice","attempted":"true","closed":"true","paid":"true","livemode":"false","attempt_count":"1","amount_due":"0","currency":"usd","starting_balance":"0","ending_balance":"0","next_payment_attempt":null,"charge":"ch_00000000000000","discount":null,"application_fee":null,"subscription":"su_00000000000000","description":null}},    "controller": "stripe_event/webhook",    "action": "event"  }  

Under development environment,

#<Stripe::Event:0x3fce66d141f0 id=test_evt_2> JSON: {    "id": "test_evt_2",    "created": 1326853478,    "livemode": false,    "type": "invoice.payment_succeeded",    "object": "event",    "data": {"object":{"id":"in_00000000000000","date":1394018368,"period_start":1394018368,"period_end":1394018368,"lines":{"object":"list","data":[{"id":"test_ii_1","object":"invoiceitem","date":1349738920,"amount":300,"livemode":false,"proration":true,"currency":"jpy","customer":"cus_test","description":"300 charged","metadata":{},"invoice":null,"subscription":null,"type":"invoiceitem"}],"url":"/v1/hashs","has_more":false},"subtotal":30000,"total":30000,"customer":"cus_00000000000000","object":"invoice","attempted":true,"closed":true,"paid":true,"livemode":false,"attempt_count":1,"amount_due":0,"currency":"usd","starting_balance":0,"ending_balance":0,"next_payment_attempt":null,"charge":"ch_00000000000000","discount":null,"application_fee":null,"subscription":"su_00000000000000","metadata":{},"description":null}}  }  

Any ideas about pitfalls in test under test environment.

No comments:

Post a Comment