Wednesday, September 28, 2016

nested form, attribute from associated model | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

nested form, attribute from associated model | Fixed issues


nested form, attribute from associated model

Posted: 28 Sep 2016 07:45 AM PDT

I have an Agenda model that has_many timeslots. A Timeslot belongs_to an Agenda.

My Agenda form uses nested attributes to collect and persist the timeslot information. The Agenda model has a begin_date field.

The Timeslot model has a virtual attribute called time_range to set the Timeslot:tstart and Timeslot:tend attributes. I use this approach to have one form field for both start and end times.

class Timeslot < ActiveRecord::Base    belongs_to :agenda      validates_presence_of :tstart, :tend      def time_range=(val)      self.tstart, self.tend = val.split(' - ').map { |v| Time.zone.parse(v) }    end      def time_range      [tstart, tend].map { |t| t.strftime "%H:%M" }.join(' - ') if tstart && tend    end    end  

In order to set the appropriate date for tstart and tend, I need the value of the begin_at attribute from the Agenda model in my time_range method.

Any ideas on how?

Active Record Rails Inheritance - Auto Type casting based on type

Posted: 28 Sep 2016 07:40 AM PDT

My scenario


-> User has many machines

-> Machines can have 5 types

-> each machine type has its own processing mechanism.

-> I want to use type column to see which class this row belongs to. (Rails inheritance approach) as explained in this link Link.


My Question


-> access a machine from database e.g machine = Machine.first

-> then call machine.process (this process method should be called based upon the type of this machine). (I am expecting some type casting stuff here.)

Note: Each machine type has its process implementation which is different from other and it implemented in its own class.

I want to know best approach to implement this. Any help is appreciated.

Getting an error while creating customer profile in authorize.net

Posted: 28 Sep 2016 07:36 AM PDT

I am creating the Customer Profile in which i want to store shipping address of customer. For this the code is -

  customer_profile_request = CreateCustomerProfileRequest.new    customer_profile_request.profile = CustomerProfileType.new(Digest::MD5.hexdigest('asda')[0,10], user.full_name, user.email,nil,nil)    full_address = user.customer_addresses.primary_address.try(:truncate_full_address) || 'Address'    customer_profile_request.profile.shipToList = CustomerAddressType.new(user.first_name,       user.last_name, nil, full_address,       user.customer_addresses.primary_address.city,       user.customer_addresses.primary_address.state, user.customer_detail.zipcode, nil, nil, nil)    customer_profile_response = initialize_transaction.create_customer_profile(customer_profile_request)  

And i am getting an error -

"The element 'shipToList' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' cannot contain text. List of possible elements expected: 'firstName, lastName, company, address, city, state, zip, country, phoneNumber, faxNumber, email' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."

Am i missing something?

Ruby on Rails solr textbox filter/facet

Posted: 28 Sep 2016 07:14 AM PDT

So im trying to implement a TextBox in the facet area , that will get what the user has typed and make it a facet value and filter the results with it!

Any ideas ?

Here's how im using facets atm

View:

<h6>Μάρκα</h6>      <ul class="facetlist">          <% for row in @search.facet(:make).rows %>          <li>              <% if params[:make].blank? %>              <%= link_to(row.value, params.merge(:page  => 1,:make => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>              <% else %>              <strong><%= row.value %></strong> (<%= link_to "remove", :make => nil %>)              <% end %>          </li>          <% end %>      </ul>  

Controller

def search      @search = Sunspot.search(Classified ) do           paginate(:page => params[:page] || 1, :per_page => 10)          order_by(:created_at , :desc)          fulltext params[:search]          with(:created_at)            active_make = with(:make , params[:make]) if params[:make].present?                   facet(:make)                  end        @classifieds = @search.results    end  

So now :make fields are rendered as facets and i can filter my results by clicking on them (which i suppose passes a parameter) , but how can i do this with a textbox? i tried various ways and failed

Typeahead and tagging

Posted: 28 Sep 2016 07:31 AM PDT

I have a route in my rails app that return a json array with all the tags that already been used. I want to use this array to help user write tags using Bootstrap Tags Input and Typeahead.

$.getJSON(      //path to json,      function(data) {          // data is an array like: ["tag1", "tag2", "tag3"]          var tagnames = new Bloodhound({            datumTokenizer: Bloodhound.tokenizers.whitespace,            queryTokenizer: Bloodhound.tokenizers.whitespace,            locals: data          });            $('#input_target').tagsinput({            typeaheadjs: {              name: 'tagnames',              source: tagnames            }          });      }  );  

I have tried this way and the way described on Bootstrap Tags Input but none of them works. What am I doing wrong?

How can I avoid deadlocks on my database when using ActiveJob in Rails?

Posted: 28 Sep 2016 07:06 AM PDT

I haven't had a lot of experience with deadlocking issues in the past, but the more I try to work with ActiveJob and concurrently processing those jobs, I'm running into this problem. An example of one Job that is creating it is shown below. The way it operates is I start ImportGameParticipationsJob and it queues up a bunch of CreateOrUpdateGameParticipationJobs.

When attempting to prevent my SQL Server from alerting me to a ton of deadlock errors, where is the cause likely happening below? Can I get a deadlock from simply selecting records to populate an object? Or can it really only happen when I'm attempting to save/update the record within my process_records method below when saving?

ImportGameParticipationsJob

class ImportGameParticipationsJob < ActiveJob::Base    queue_as :default      def perform(*args)      import_participations(args.first.presence)    end      def import_participations(*args)      games = Game.where(season: 2016)      games.each do |extract_record|        CreateOrUpdateGameParticipationJob.perform_later(extract_record.game_key)      end    end     end  

CreateOrUpdateGameParticipationJob

class CreateOrUpdateGameParticipationJob < ActiveJob::Base    queue_as :import_queue       def perform(*args)       if args.first.present?         game_key = args.first           # get all particpations for a given game         game_participations = GameRoster.where(game_key: game_key)         process_records(game_participations)       end     end       def process_records(participations)       # Loop through participations and build record for saving...       participations.each do |participation|         if participation.try(:player_id)           record = create_or_find(participation)           record = update_record(record, participation)         end           begin           if record.valid?             record.save           else             end         rescue Exception => e           end       end     end       def create_or_find(participation)       participation_record = GameParticipation.where(         game_id: participation.game.try(:id),         player_id: participation.player.try(:id))         .first_or_initialize do |record|           record.game = Game.find_by(game_key: participation.game_key)           record.player   = Player.find_by(id: participation.player_id)           record.club     = Club.find_by(club_id: participation.club_id)           record.status   = parse_status(participation.player_status)       end       return participation_record     end       def update_record(record, record)       old_status = record.status       new_status = parse_status(record.player_status)       if old_status != new_status         record.new_status = record.player_status         record.comment    = "status was updated via participations import job"       end       return record     end    end  

Why including Rescuable module doesn't work?

Posted: 28 Sep 2016 07:42 AM PDT

class MyKlass      include ActiveSupport::Rescuable      rescue_from Exception do      return "rescued"    end      #other stuff  end  

MyKlass is pure ruby object, but defined inside Rails application.

If I try to invoke MyKlass instance in rails console and then apply to it method which certainly should raise Exception, nothing happens other than error expected to be rescued.

Expecting messages that do not change application state in RSpec

Posted: 28 Sep 2016 06:54 AM PDT

In testing literature, you hear not to assert on outgoing messages unless they change the state of something else. In other words, query messages that don't affect state are stubbed with allow().with().and_return().

The problem I have with this method is that when all of these allows happen in the before block, when a method's parameters change, every test will fail. This is because the allow().with() block will not be triggered.

Consider this example:

describe('#some_endpoint') do    let(:another_class) { instance_double(AnotherClass) }    let(:presenter) { instance_double(Presenter) }      before do      allow(another_class).to receive(:presenter).with(some_args).and_return(presenter)    end      it 'assigns the correct presenter' do      get :some_endpoint      expect(assigns(:presenter)).to eq(presenter)    end      it 'responds with ok status' do      get :some_endpoint      expect(subject).to have_http_status(:ok)    end      it 'does something else' do      .....    end  end  

This example follows the testing literature and does not assert on another_class.presenter because that is a query message. If, however, the expected arguments to the presenter, some_args changes in the code, all tests will fail. This is much easier to debug if only the assigns the correct presenter test fails, which is the actual failure in the case of an argument change; because the presenter that is returned is not the correct presenter. The following tests would accomplish that goal:

describe('#some_endpoint') do    let(:another_class) { instance_double(AnotherClass) }    let(:presenter) { instance_double(Presenter) }      before do      allow(another_class).to receive(:presenter).and_return(presenter)    end      it 'assigns the correct presenter' do      get :some_endpoint      expect(another_class).to have_received(presenter).with(some_args)      expect(assigns(:presenter)).to eq(presenter)    end      it 'responds with ok status' do      get :some_endpoint      expect(subject).to have_http_status(:ok)    end      it 'does something else' do      .....    end  end  

What are the disadvantages of testing this way? I only see advantages. If this is the case, why is it that the testing community suggests not testing query messages?

bootstrap search rails look and feel

Posted: 28 Sep 2016 06:57 AM PDT

I've got a nice bootstrap navigation menu with a search box in it.

I've got it in a partial file...

      <form class="navbar-form navbar-left">      <div class="form-group">        <input type="text" class="form-control" placeholder="Search">      </div>      <button type="submit" class="btn btn-default">Submit</button>    </form>  

I like the layout of this search box. Unfortunately, I can't figure out how to get my rails search box to look the same...

<%= search_form_for @search do |f| %>  <div class="field">    <%= f.label :title_or_template_cont, "Search" %>    <%= f.text_field :title_or_template_cont %>      </div>   <div class="actions">  <%= f.submit "Search" %>  

What changes do I need to make in my rails form to look like the bootstrap search box?

I tried a few classes within the rails search box, but wasn't close to the way it looked.

Any suggestions?

How do I test Devise confirm with Minitest?

Posted: 28 Sep 2016 06:35 AM PDT

How can I construct a get to test devise confirmation in my Rails 5 application with minitest?

I'm trying to test Devise confirmation with minitest and getting a 401 response instead of a 200. In the application it works correctly.

# registrations_controller_test.rb  require 'test_helper'    class RegistrationsControllerTest < ActionController::TestCase      def setup      @controller = Users::RegistrationsController.new    end      #Users::RegistrationsController    test 'register new user' do      email = 'register_new_user@test.com'      @request.env["devise.mapping"] = Devise.mappings[:user]      post :create, params: { user: {email: email, password: 'alksdjflksdjfkj'}}        confirm_email = ActionMailer::Base.deliveries.last      u = User.find_by(email: email)        refute u.confirmed?      assert_match "confirmation_token=#{u.confirmation_token}", confirm_email.body.to_s      assert_equal email, confirm_email.to[0]      #/users/confirmation?confirmation_token=shsgqVVV2tayLL9Z139s      #devise/confirmations#show        @controller = Devise::ConfirmationsController.new      @request.env["devise.mapping"] = Devise.mappings[:user]      get "show", params: {confirmation_token: u.confirmation_token}      # response.headers are {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Location"=>"http://test.host/users/sign_in", "Content-Type"=>"text/html; charset=utf-8"}        assert u.confirmed?  #fails      end    end  

After I do get "show", params: {confirmation_token: u.confirmation_token}

The response is a 401 and a redirect to http://test.host/users/sign_in

I'm not sure if this is a routing issue?

rails routes | grep confirmation                 user_confirmation POST     /users/confirmation(.:format)                  devise/confirmations#create             new_user_confirmation GET      /users/confirmation/new(.:format)              devise/confirmations#new                                   GET      /users/confirmation(.:format)                  devise/confirmations#show  

but I noticed response.url is different in test and in my development app:

test: /users?confirmation_token=sxhMSykFUk4VPsxcA6-M
dev: /users/confirmation?confirmation_token=LGoSov1mfaxGu_cpsdnG

Rails HTML Table: <tr> tag doesn't do anything

Posted: 28 Sep 2016 06:50 AM PDT

  <% for ws in @user.workstations %>      <tr class="red">        <td class="td_workstation"> <%= ws.name %> </td>        <td class="td_workstation"> <%= ws.applications %> </td>      </tr>    <% end %>  

The class "red" is supposed to make the background red, but it doesn't do anything. Why isn't it affecting the rows??????

.red {    background: red;    font-size: 60px;  }    .td_workstation, .th_workstation {  border: 1px solid #dddddd;  }  

Data association within a service oriented architecture

Posted: 28 Sep 2016 07:07 AM PDT

We have 3 API applications build as a sort of service oriented architecture. I say sort of because it does not totally embrace the SOA tenets as I'm about to explain with this simple use case.

Use case

We have a Client API which is responsible for handling clients contact information. On the other end, we have a Sales API which take care of quotation and billing. This is the part when it becomes messy (IMHO). The sales API has an orders table which has a client_id attribute in order to know which client is associated to it.

Problem

As I said, the architecture has been built as a sort of SOA, meaning that each service has it's own database. So to continue with our use case, the sales API is storing at some point a client_id, client that does not actually exists in the context of this API because the Client API is the one holding this responsability.

For example, let's say that in order to create a new sales' order, I need to check that the associated client (send as client_id in a POST api.sales.domain.com/orders) actually exists. How to handle such case? For now we do a HTTP request against the Client API and check for a 200 response. What if we want to return embbed client data within an order json:

{      "id": 2,      "status": "pending",      "client": {          "name": "John Doe",          "address": "123 street"      }  }  

As we are using Rails, we use the gem Her in order kinda deal with these cases. But it does not really feel right.

is there a better way to do it?

Why does Rails 5 on Windows 10 run significantly faster than Windows 7?

Posted: 28 Sep 2016 06:26 AM PDT

I switched over to my Windows 10 machine after the Windows 7 one was unavailable, git clone my app and ran rspec in 5 seconds, compared to 17 seconds on Windows 7.

Is there some new feature in Rails 5 that makes it super fast on Windows 10?

Here's my gem file if it helps, I didn't see anything special on it that suggest there was something like Spring.

gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  gem 'pg'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.2'  gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'    group :test do    gem 'shoulda-matchers', '~> 3.1'    gem 'factory_girl_rails'    gem 'simplecov', :require => false  end    group :development, :test do    gem 'byebug', platform: :mri    gem 'rspec-rails', '~> 3.5'  end    group :development do    gem 'web-console'    gem "better_errors"    gem "binding_of_caller"  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]    gem 'bootstrap-sass', '~> 3.3.6'  gem 'figaro'  gem 'indeed_api'  gem 'nokogiri'  gem 'numbers_in_words'  gem 'pry'  gem 'resque', "~> 1.22.0" # Heroku requires 1.22.0  Read more here: https://devcenter.heroku.com/articles/queuing-ruby-resque  gem 'rake', "~> 11.3.0"  gem 'sinatra', github: 'sinatra/sinatra', branch: 'master' # Specifically for resque front-end    gem 'rails-controller-testing'  

Phusion Passenger shutting down

Posted: 28 Sep 2016 06:23 AM PDT

I am trying to log to STDOUT using APACHE + PASSENGER and i am noticing that passenger gets shutdown after first request. (Signal received. Gracefully shutting down... (send signal 2 more time(s) to force shutdown)).

However, when logging into file, the application works fine.

Any help in clearing this confusion would be highly appreciated!

Thanks in advance.

PS : i am running Apache in foreground and getitng this error :-

[mpm_event:notice] [pid 4249:tid 139620754126656] AH00492: caught SIGWINCH, shutting down gracefully

Unable to autoload constant Api::V1::UsersController

Posted: 28 Sep 2016 06:31 AM PDT

I've been developing API, but when I access the endpoint Unable to autoload constant Api::V1::UsersController, expected /Users/toshikiinami/Desktop/billing/app/controllers/api/v1/users_controller.rb to define it comes out.

  • I use rails 4.2.3

Any ideas to configure the subdomain endpoint properly?

config/routes.rb

Rails.application.routes.draw do        namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/'  do      scope module: :v1 do        resources :users, only: [:index]      end    end  end  

controllers/api/v1/users_controller.rb

class UsersController < ActionController::Base    def index      render 'test' => 'json'    end  end  

/etc/hosts

##  # Host Database  #  # localhost is used to configure the loopback interface  # when the system is booting.  Do not change this entry.  ##  127.0.0.1 localhost  127.0.0.1 api.localhost.local  

undefined method `filter' for #<Class:0x007fc0600be140> edited, need more help please

Posted: 28 Sep 2016 07:45 AM PDT

Please see edit below

I've received precious help from another question but now I have this error undefined methodfilter' for #`

I am trying to filter by categories (Category were created in the console, like Category.create(name: "Ruby") and so on...)

Looking forward for your help, thanks in advance :)

2.3.1 :009 > Category.all    Category Load (0.2ms)  SELECT "categories".* FROM "categories"   => #<ActiveRecord::Relation [#<Category id: 1, name: "Ruby", created_at: "2016-09-26 09:03:17", updated_at: "2016-09-26 09:03:17">, #<Category id: 2, name: "Rails4", created_at: "2016-09-26 09:03:25", updated_at: "2016-09-27 14:32:39">, #<Category id: 3, name: "Rails5", created_at: "2016-09-26 09:03:30", updated_at: "2016-09-27 14:35:25">, #<Category id: 4, name: "Heroku", created_at: "2016-09-26 09:03:35", updated_at: "2016-09-27 14:35:47">, #<Category id: 5, name: "AWS-Amazon", created_at: "2016-09-26 09:03:43", updated_at: "2016-09-26 09:03:43">]>  

my model tuto

class Tuto < ActiveRecord::Base    acts_as_votable    belongs_to :user    belongs_to :category    validates :category_id, presence: true        def self.search(search)      if search        where(["title LIKE ?","%#{search}%"]).order('created_at DESC')      else        all      end    end  #moved this method in category.rb    #def self.filter(filter)      #if filter        #where(["name LIKE ?","%#{filter}%"]).order('created_at DESC')      #else        #all      

No comments:

Post a Comment