Monday, May 9, 2016

Rails 4.2 perform custom search via ransackers | Fixed issues

Rails 4.2 perform custom search via ransackers | Fixed issues


Rails 4.2 perform custom search via ransackers

Posted: 09 May 2016 06:58 AM PDT

In my app I use rails-4.2 width ransack. I like to perform search customization in order to search rows that have a integer attribute = 0 or attribute >= 1. I've a price attribute in orders table. I like to define custom search like this:

In a view:

f.select :price_exists_true, [["No", 0], ["Yes", 1]]  

In a model:

If price == 0 or nil => "No"    If price >=1 => "Yes"  

Can you explain me how to do that? Many tanks in advance.

Stefano

Paperclip validation of StringIO not valid

Posted: 09 May 2016 06:57 AM PDT

I would like to use the Paperclip gem (4.3.6) to stream a file from a 3rd party API and use the body of the HTTP response as an attachment on an ActiveRecord model representing a Fax.

class Fax    has_attached_file :fax_document    validates_attachment_content_type :fax_document, content_type: { content_type: ["application/pdf", "application/octet-stream"] }  end  

I am using the code below to get the HTTP response from the API server and save it as an attachment on the Fax model. (Code below is modified slightly for brevity).

#get the HTTP response body  response = download(url)    #add the necessary attributes to the StringIO class. This technique is demonstrated in multiple SO posts.  file = StringIO.new(response)  file.class.class_eval { attr_accessor :original_filename, :content_type }  file.original_filename = "fax.pdf"  file.content_type = 'application/pdf'    #save the attachment  fax = Fax.new  fax.fax_document = file  fax.save  

The response variable contains what looks like a string representation of a pdf binary object and fax.save raises a content_type not valid error. If I explicitly relax the Paperclip validation on the fax model using do_not_validate_attachment_file_type :fax_document, then the attachment will save properly.

I suspect that Paperclip content type validation is failing because it can't tell that that the content returned from is in fact 'application/pdf'.

Why is Paperclip raising a content_type not valid error? How do I tell Paperclip that the body of the response is a pdf?

Error with jQuery and rails

Posted: 09 May 2016 06:58 AM PDT

I got a problem with jQuery.ui and Rails. I try to solve this error since 6 hours but I can't find a solution. This is especially annoying that it seems simple. Sure I am missing something.

When I add <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> to the head of my application.html.erb, it works but only if the input is placed inside application.html.erb :

<%= javascript_include_tag "application", "data-turbolinks-track" => true %>    <form method="post">     Date:<input type="text" id="datepicker" name="datepicker" />  </form>  

If the form is placed in ANY other view, the date picker function will not works.

in application.js:

//= require jquery  //= require jquery_ujs  //= require jquery.ui.all  //= require jquery.turbolinks   //= require turbolinks  //= require welcome  //= require subscriptions  //= require to_do_lists  //= require_tree .    $(function() {      $( "#datepicker" ).datepicker();  });  

in gemfile :

gem 'jquery-ui-rails', '~> 5.0', '>= 5.0.5'  

in application.css :

/*   *= require_self   *= require jquery.ui.all  */  

I face two problems :

  1. First, jQuery-ui gem won't works
  2. Second, even if I call the script in the head of my app, it works only with a form in application.html.erb

Any idea ?

rails : how to set locale in elasticsearch use chewy gem

Posted: 09 May 2016 06:50 AM PDT

I use elasticsearch by gem Chewy. and I use Globalize gem to translation. I have a model Location, and translate attribute name of location. But chewy only update last data, don't update data with different locale. I want to chewy update both data (with locale :en , :fr, ..) How to set or config globalize in elasticsearch

What are the correct file locations when adding a Rails backend to a JS/HTML/CSS application?

Posted: 09 May 2016 06:49 AM PDT

I made a game in JavaScript. I have a directory called Game, and it contains:

  • index.html
  • app.css
  • imgs
  • lib
  • vendor

Inside of lib I have my own javascript files. Inside of vendor I have a javascript file from a third party, that is used for a specific functionality in the game. I'm using webpack to bundle my modules, and so inside of lib I also keep my bundle.js file.

I now want to add a Rails backend to the game. I am very familiar with writing code using Ruby on Rails, but there are holes in my knowledge of where certain files should go in the directory structure.

If I transform my purely javascript/html/css game into a Rails application with a single page (the root page with the game on it), where do the files I listed above go?

Here is how I think it would be:

  • index.html would become my app/views/layouts/application.html.erb
  • app.css would become app/assets/stylesheets/application.css
  • the contents of my imgs folder would go in /public (actually it has never made sense to me why I it never works when I put my images in app/assets/images, but that's another story)
  • the contents of my lib folder would go in app/assets/javascripts (hope I don't have the same issue as with my images)
  • and the javascript file contained in my vendor folder would go in /vendor

Is this correct? Are there any other considerations to take into account?

Rails new gives "Could not find proper version of railties (4.2.5.1) in any of the sources" error

Posted: 09 May 2016 06:42 AM PDT

I am trying to use Rails 5.0.0.rc1 with Ruby 2.3.1. However, if I try to create a new project within my "programming" directory, I get this:

 ➜  ~/Documents/Programming  rails new foo  Could not find proper version of railties (4.2.5.1) in any of the sources  Run `bundle install` to install missing gems.  

If I do a gem list, the only rails version I have installed in 5.0.0.rc1. What is interesting is I get the same error when I do rails -v, but do not when I do it from my home directory:

 ➜  ~  rails -v  Rails 5.0.0.rc1   ➜  ~  cd Documents/Programming   ➜  ~/Documents/Programming  rails -v  Could not find proper version of railties (4.2.5.1) in any of the sources  Run `bundle install` to install missing gems.  

I have tried uninstalling and reinstalling both rails and railties with the same result. I am using rvm and had to do

gem install nokogiri -- --use-system-libraries  

to install nokogiri.

How to make jquery stack/work together

Posted: 09 May 2016 06:56 AM PDT

Hey i'm a new programmer getting started in RoR, HTML, CSS and JS ran into a bit of a problem that im not to sure how to fix, searched the web and could't find an answer so here it is.

I have a date picker and 2 dropdown menu but i cant get them to work together, each time i select something it refreshes everything. here is what the code looks like.

        <script type="text/javascript">                          $(function() {                              function cb(start, end) {                                  $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));                                }                              cb(moment(), moment());                                $('#reportrange').daterangepicker({                                  ranges: {                                     'Today': [moment(), moment()],                                     'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],                                     'Last 7 Days': [moment().subtract(6, 'days'), moment()],                                     'Last 30 Days': [moment().subtract(29, 'days'), moment()],                                     'This Month': [moment().startOf('month'), moment().endOf('month')],                                     'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],                                     'This Year': [moment().startOf('year'), moment()]                                  }                              }, cb);                                    $('#reportrange').on('apply.daterangepicker', function(ev, picker) {                                //do something, like clearing an input                                  data = {                                      startDate: picker.startDate.format(),                                      endDate: picker.endDate.format()                                  }                                      window.location.href = "/invoices?startDate=" + data["startDate"] + "&endDate=" + data["endDate"]                              });                          });                          </script>  <script type="text/javascript">                      $(function(){                          $(".dropdown-menu li a").click(function(){                                  choice = $(this).text()                                    if(choice == "Normal"){                                      $("tr.false").show()                                      $("tr.true").hide()                                  }else if(choice == "Special"){                                          $("tr.false").hide()                                          $("tr.true").show()                                  }else if(choice == "Pudu"){                                          $("tr[data-id='2']").hide()                                          $("tr[data-id='1']").show()                                          window.location.href = "/invoices?hotel_id=" + 1                                  }else if(choice == "Kota"){                                          $("tr[data-id='1']").hide()                                          $("tr[data-id='2']").show()                                          window.location.href = "/invoices?hotel_id=" + 2                                  }else if(choice == "All"){                                          $("tr").show()                                  }                                    $(this).closest(".dropdown").find(".btn").text(choice)                                      console.log($(this))                              });                      });                  </script>  

Any help will be appreciated

Rails - submit form button does not work after AJAX render

Posted: 09 May 2016 06:33 AM PDT

I've met some issue. Inside view I have a select list. On change I invoke ajax which runs controller method. In controller method I fetch expected data from DB responding to .js.erb file. Then in .js.erb I partially render html view:

$("#games").html("<%= j(render partial: 'games', locals: { games: @games } ) %>");  

_games.html.slim

tr    - games.each do |game|      = form_tag('/games/perform', remote: true) do         tr          td = text_field_tag :title,          td = submit_tag 'Save'  

File is appending fine but when I want to submit form clicking button any actions happen. What I am doing wrong or I missed something?

When create an item within a category, the item can't get the category_id

Posted: 09 May 2016 06:22 AM PDT

I am building ecommerce using Rails and I got stuck with this problem:

When I try to create a new item within some category from a browser, the created item doesn't get an id of the category.

http://localhost:3000/categories/1/items/new

In console I can verify that params get the category_id correctly:

Parameters: {"category_id"=>"1"}

After creating the item's category_id equals to nil.

Here's my Item model file:

class Item < ActiveRecord::Base    belongs_to :category  end  

Category model:

class Category < ActiveRecord::Base    has_many :items  end  

This is my items_controller.rb file where I pass category_id to the Item:

class ItemsController < ApplicationController  # other actions are ommited      def new        @item = Item.new        @item.category_id = params[:category_id]      end  end  

Also you can look at the whole app in: https://github.com/kaneru/estore

Thanks in advance.

Mysql2::Error: Unknown column 'sum_hours' in 'field list'

Posted: 09 May 2016 06:55 AM PDT

Its been nearly 2 months since i started to learn rails for doing some modifications on a plugin of Redmine in an enterprise (as a student learning the way of "life"), but this problem is something i cant find the solution anywhere.

Let me explain:

I needed to group a huge ammount of time entries by user_id and project_id(no problems with that) but if i do this i need to Sum the hours in those groups.

The estructure is something like this:

| ID | project_id | user_id | issue_id | hours |

And this information is built up with this method :

def time_entries_for_user(user, options={})      extra_conditions = options.delete(:conditions)      return TimeEntry.select('*,sum(hours) as sum_hours').        includes(self.includes).        where(self.conditions([user], extra_conditions)).        group('issue_id, time_entries.project_id').        order('issues.id ASC')  end  

I added the select because i needed all the column plus the sum one and the group by alone works well , but i cant make the Sum columns appear. This is the json code from the result of this method:

{"test1 / SubProyectoTest1":{"logs":[{"id":24,"project_id":4,"user_id":1,"issue_id":10,"hours":6.0,"comments":"","activity_id":8,"spent_on":"2016-05-03","tyear":2016,"tmonth":5,"tweek":18,"created_on":"2016-05-03T11:07:09.000Z","updated_on":"2016-05-03T11:07:09.000Z","sum_hours":9.0}],"users":[{"id":1,.....  

The funny thing is that in other method which groups by project , the Sum column appear.

def time_entries_for_all_users(project)  return project.time_entries.select('*,sum(hours) as sum_hours').includes(self.includes).    where(self.conditions(self.users)).group('issue_id,user_id')    order('issues.id ASC')  end      {"test1 / SubProyectoTest1":{"logs":[{"id":24,"project_id":4,"user_id":1,"issue_id":10,"hours":6.0,"comments":"","activity_id":8,"spent_on":"2016-05-03","tyear":2016,"tmonth":5,"tweek":18,"created_on":"2016-05-03T11:07:09.000Z","updated_on":"2016-05-03T11:07:09.000Z","sum_hours":9.0}],"users":[{"id":1.......  

In the logs, this error shows :

ActionView::Template::Error (undefined method `sum_hours' for #)

Referring to this code on the view that renders the time entries:

 <% when l(:field_hours) %>  <strong><%= number_with_precision(time_entry.sum_hours, :precision => @precision) %></strong>  

Well, you cant call something that doesn't exists...

2º time asking for help in StackOverflow so if you need more info because i forgot to write it , do it :) .

Regards and thanks.

How to test methods in application controller? My approach makes other tests randomly crash

Posted: 09 May 2016 05:34 AM PDT

I have a simple method in the application controller:

class ApplicationController < ActionController::Base    def filename_for_export(project, type, format = nil)      buffer = "#{project.customer} - #{project.name} (#{type}, #{t 'org.name'}, #{Date.today.to_s :db})"      buffer += ".#{format}" if format      buffer    end  end  

I have the following test for it:

describe ApplicationController do    describe '#filename_for_export' do      before { @controller = ApplicationController.new }        it 'returns a good human readable filename' do        project = create(:project)        result = @controller.instance_eval{ filename_for_export(project, 'Audit') }        expect(result).to eq 'Project test customer - Project test name (Audit, Access for all, 2015-06-15)'      end    end  end  

Everything works fine. Then I added another test:

it 'appends a format extension if given' do    project = create(:project)    result = @controller.instance_eval{ filename_for_export(project, 'Audit', 'pdf') }    expect(result).to eq 'Project test customer - Project test name (Audit, Access for all, 2015-06-15).pdf'  end  

Also working fine. But interestingly, this 2nd test seems to break something which makes many other specs fail randomly:

...  rspec ./spec/features/file_upload_spec.rb:18 # File upload displays a preview of an uploaded file  rspec ./spec/features/file_upload_spec.rb:4 # File upload allows to upload a file  rspec ./spec/features/file_upload_spec.rb:27 # File upload displays a preview of an uploaded file (from the temporary cache) after a re-display of the form  rspec ./spec/features/file_upload_spec.rb:60 # File upload allows to remove a file  rspec ./spec/features/markdown_spec.rb:4 # Markdown uses Pandoc as converter for inline markdown  rspec ./spec/features/users/destroy_spec.rb:22 # Deleting user signed in as admin grants permission to delete other user  rspec ./spec/features/success_criteria/show_spec.rb:6 # Showing success criterion displays a success criterion  rspec ./spec/features/boilerplate_originals/edit_spec.rb:11 # Editing boilerplate grants permission to edit a boilerplate  ...  

It's always another set of specs that fail (I guess it's some order issue), but I have no idea what could be breaking things? This 2nd spec doesn't do anything different than the 1st one, so what could it break?

How to improve code in Views on Ruby on Rails

Posted: 09 May 2016 05:24 AM PDT

I have code in file views name: _result.html.erb, this file is rendered from file show.html.erb, both file in one folder

File _result.html.erb      <% if @lesson.answers.at(f.index).is_correct %>        <% if @lesson.answers.at(f.index).id == answer.id %>          <li class="text-success">            <%= f.radio_button :answer_id, answer.id, disabled: true %>            <%= answer.content %>          </li>        <% else %>          <li>            <%= f.radio_button :answer_id, answer.id, disabled: true %>            <%= answer.content %>          </li>        <% end %>      <% else %>        <% if @lesson.answers.at(f.index).id == answer.id %>          <li class="text-danger">            <%= f.radio_button :answer_id, answer.id, disabled: true %>            <%= answer.content %>          </li>        <% else %>          <li>            <%= f.radio_button :answer_id, answer.id, disabled: true %>            <%= answer.content %>          </li>        <% end %>      <% end %>  

And I want to improve this code in file _result.html.erb for shorter, help me please!!!

File show.html  <% provide :title, t("start_lesson") %>  <h1><%= @course.name %></h1>  <h2><%= @course.description %></h2>  <h3><%= t "title_question" %></h3>    <% if @lesson.finished.present? %>    <h4>      <%= t "score" %>:      <%= @lesson.results.is_correct_answers.count %> /      <%= @lesson.words.count %>    </h4>  <% end %>    <%= form_for [@course, @lesson] do |f| %>    <%= f.fields_for :results do |builder| %>      <ul class="list-unstyled">        <li>          <%= "#{builder.index + 1}." %>          <%= @words.at(builder.index).content %>        </li>        <ul class="list-unstyled">          <% @words.at(builder.index).answers.each do |answer| %>            <% if @lesson.finished.nil? %>              <li>                <%= answer.content %>                <%= builder.radio_button :answer_id, answer.id %>                <%= builder.hidden_field :word_id, value: answer.word.id %>              </li>            <% else %>                <%= render "result", f: builder, answer: answer %>            <% end %>          <% end %>        </ul>      </ul>    <% end %>    <% if @lesson.finished.nil? %>      <%= f.submit t("submit"), class: "btn btn-primary" %>    <% end %>  <% end %>  

how to get real post.id in model with freindly_id

Posted: 09 May 2016 05:47 AM PDT

I have a model called post that has its :id modified with friendly_id, how can I get the real :id of the current post while inside the model?

I want to do something like this: '

after_create :set_post_id  def set_post_id    post_id = self.post.id    self.update_attributes(:post_id => post_id)  end  

uploading 3d object using paperclip rails 4 Issue

Posted: 09 May 2016 05:32 AM PDT

I have a 3d model(.awd) extension to upload on rails app using paperclip. This error always appear to my logs Content Type Spoof: Filename Sample.awd. I try to used do_not_validate_attachment_file_type, but still having the same error. Hoping for the solution on my problem.

how to eliminate empty arrays from an array of arrays in ruby?

Posted: 09 May 2016 05:38 AM PDT

i have an array of arrays. from this i want to eliminate the empty arrays.

iam using reject!(&:empty?) method. but it is giving me unexpected results.

2.2.2 :306 >   array = ["yes","yes","yes"]   => ["yes", "yes", "yes"]   2.2.2 :307 > array.split("no")   => [["yes", "yes", "yes"]]   2.2.2 :308 > array.split("no").reject!(&:empty?)   => nil   2.2.2 :309 > array_with_no = ["yes","yes","yes","no"]   => ["yes", "yes", "yes", "no"]   2.2.2 :310 > array_with_no.split("no")   => [["yes", "yes", "yes"], []]   2.2.2 :311 > array.split("no").reject!(&:empty?)   => nil   2.2.2 :312 > array_with_no.split("no").reject!(&:empty?)   => [["yes", "yes", "yes"]]   2.2.2 :313 >   

i want the result where when there is no empty array to eliminate, then it should return the same array instead of returning nil

How to implement multi device Login in rails 3?

Posted: 09 May 2016 05:39 AM PDT

I'm using clearance(1.3.0) gem with rails(3.2.18) and ruby(2.0). Now i want to implement multi device login & maintain their devise token to push notification. When i logout from one device, it should not affect the other login.

How to refresh a div without reloading the entire page?

Posted: 09 May 2016 05:01 AM PDT

I have a div and I want to refresh its content without reloading the entire page.

I tried many times with many methods (ajax call, javascript, etc...), but I don't have did it.

My div displays the entire content of ModelName.all And in this particular div, we can add new entities (thanks to a form) of the Model I use.

I display this div thanks to a Rails Partial View.

Currently, I use this when the user submit the form :

$('#ArticlesDiv').html("<%= escape_javascript (render partial: 'articles') %>");  

But it seems my partial view doesn't have an up-to-date model. Because before I add the new entity, I see for example 5 elements, and after I add the new entity, I see again 5 elements. For test purposes, I use a javascript alert which displays ModelName.all.count

And the alert displays 5 ! But when I look at my database content (before the alert), I can see 6 elements ! And when I refresh my page manually, the div displays 6 elements.

Code to explain :

The main view :

<div id="ArticlesDiv">    <%= render(:partial => "articles") %>  </div>  

_articles (the partial view) :

<script>    alert('<%=Article.all.count%>');  </script>    <% Article.all.each do |article|) %>    <strong><%= article.name %></strong><br />    <% end %>  

My goal is to have a smooth interface which it doesn't reload the entire page any times you add an other article.

Rails/PostgreSQL: Adding character limit to text

Posted: 09 May 2016 06:01 AM PDT

I want to implement a character limit to a data value on my PostgreSQL database for my Ruby on Rails application. Currently my database table looks like this:

create_table "applications", force: :cascade do |t|      t.string   "name"      t.string   "gender"      t.date     "date_of_birth"      t.string   "gpa"      t.text     "essay"      t.datetime "created_at",    null: false      t.datetime "updated_at",    null: false  end  

I want to change it so the "essay" only allows 10000 characters. From my limited understanding of PostgreSQL, text is unlimited by default whereas string is for 255 characters or less. I thought about implementing a Javascript conditional to not let the user hit the submission button in the client if the text is over 1,000 characters, but of course a tech savvy user could change that. What would be the most optimal way to do this?

ruby : when to use 'load' to load file instead of 'require' [duplicate]

Posted: 09 May 2016 05:20 AM PDT

This question already has an answer here:

i know the basic difference between load and require statement. load loads the file multiple time even if it is already loaded and require loads the file only once.

i want to know when to use load statement over require statement. if possible then please explain with small example.

Thanks,

Selected values in form_for rails

Posted: 09 May 2016 04:41 AM PDT

Only the date, out of the first_city and last:city empty. How to get selected value? view:

<%= form_for (@orders) do |f| %>  <p>route/p>      <%= f.select(:first_city, @city_select, prompt: "first") %>    <%= f.select(:last_city, @city_select, prompt: "second") %>    <%= f.text_field :date_trip %><br>    <%= f.submit "next", class: "btn" %>  <% end %>   

controller

def orderdate  @orders=Order.new  @city_select = City.select(:name).distinct.map { |u| [u.name, u.id]}  end    def create  @order=current_user.orders.build(order_params)  end  

Create different database per account

Posted: 09 May 2016 05:27 AM PDT

I am new to ruby on rails. I am using mongomapper and I want to create single database per account. Suppose If user will login, new database will create with the username of the login user and if already created then it will switch to that database. I am trying with the following code in the model : class User include MongoMapper::Document include ActionView::Helpers connection(Mongo::Connection.new('localhost', 27017)) set_database_name "#{current_user.username} key :name, String key :email, String, :required => true key :username, String, :required => true, :unique => true end

But I am not getting username. If I put this code "connection(Mongo::Connection.new('localhost', 27017))" in controller its giving error. Is there any way to establish new database connection from application controller. Waiting for the solution, thanks in advance.

Rails Server does not load after closing terminal

Posted: 09 May 2016 05:48 AM PDT

I am trying to run the rail server command in terminal on my mac(el captain 10.11.4). Every time I close the terminal window it results in this:

/Users/pinkelephant/.rvm/gems/ruby-2.3.0/gems/debug_inspector-0.0.2/lib/debug_inspector.rb:6:in `require': incompatible library version - /Users/pinkelephant/.rvm/gems/ruby-2.3.0/gems/debug_inspector-0.0.2/lib/debug_inspector.bundle (fatal)  

I then can get it to work if I completely reinstall ruby...not ideal. Bundle install does not help either. Any ideas?

Rails Associated Table Does not update

Posted: 09 May 2016 04:28 AM PDT

I have two models

influencers(id, first_name, ....)  influencer_authorizations(id, provider, provider_uid, oauth_token, ....)  

influencers has_many influencer_authorizations

I am trying to login or Sign the Influencer

  # 1. Check if the Token is Valid    # 2. Check if the influencer has the authorization for that facebook_uid    # 3. If no - then create a new influencer    # 4. If yes - Then he is loging in. so update the token and log him in  

But when a OLD user tries to login the OAuth Token is not getting updated

Facebook Controller

def create        @facebook_login = FacebookClient.new(facebook_user_token)        if @facebook_login.create        render :show      else        render :error      end      end  

Facebook Client

class FacebookClient    def initialize(token)      @token = token      @client = Koala::Facebook::API.new(token)    end      attr_reader :influencer      def create      @influencer = new_or_existing_influencer        save_influencer    end      def errors      {        facebook_error: @facebook_errors      }    end      private      attr_reader :client      def new_or_existing_influencer      influencer = Influencer.joins(:influencer_authorizations).where(                          :influencer_authorizations => {                            provider: 'facebook',                            provider_uid: provider_uid                          }                        ).first_or_initialize      influencer    end      def save_influencer      set_influencer_details if @influencer.new_record?      set_influencer_authorization_details if @influencer.new_record?        @influencer.influencer_authorizations[0].oauth_token = @token if !influencer.new_record?        @influencer.save    end      def set_influencer_details      @influencer.assign_attributes(          first_name: first_name,          last_name: last_name,          email: email,          bio: bio,          date_of_birth: birthday,          gender: gender,          location: location      )    end      def set_influencer_authorization_details      @influencer.influencer_authorizations.build(          provider: 'facebook',          provider_uid: provider_uid,          oauth_token: @token,          social_account: SocialAccount.friendly.find('facebook')      )    end      def basic_information      begin         @basic_information ||= client.get_object("me?fields=id,first_name,last_name,name,bio,about,birthday,email,timezone,gender,location,hometown,currency,locale,devices")       rescue Koala::Facebook::APIError => exc         @facebook_errors = exc.message      end    end      def provider_uid      basic_information["id"]    end      def first_name      basic_information["first_name"]    end      def last_name      basic_information["last_name"]    end      def name      basic_information["name"]    end      def email      basic_information["email"]    end      def bio      basic_information["bio"]    end      def location      basic_information["location"].present? ? basic_information["location"]["name"] : ""    end      def birthday      basic_information["birthday"].present? ? Date.strptime(basic_information["birthday"], "%m/%d/%Y") : ""    end      def gender      basic_information["gender"].present? ? basic_information["gender"] : "not_specified"    end    end  

Just before saving on inspect the Oauth Token is set to @influencer.influencer_authorizations[0].oauth_token

What is a systematic approach to debug intermittently failing specs?

Posted: 09 May 2016 04:56 AM PDT

I have four tests in my Capybara/Rspec suite that keep failing (a real problem for CI deployment).

The worst thing, these tests are failing intermittently, and often only when the entire suite is run, making it difficult to debug.

They are all ajax requests, either submitting a remote form or clicking a remote link, followed by expect(page).to have_content 'My Flash Message'.

These tests even fail intermittently within the same test cycle. For example, I have several models that behave similarly, so I am iterating through them to test.

e.g.,   ['Country', 'State', 'City'].each do |object|    let(:target) { create object.to_sym }    it 'runs my frustrating test' do     end  end  

Sometimes country fails, sometimes state, sometimes everything passes.

I have tried adding wait: 30 to the expect statement. I have tried adding sleep 30 before the expect statement. I'm still getting intermittent passes.

There is quite a bit of information out there describing finicky ajax tests, but I have not found much about how to debug and fix these kinds of problems.

I'm really grateful for any advise or pointers from others, before I pull all my hair out!!

Creating a variable via the form rails

Posted: 09 May 2016 04:07 AM PDT

Value the variables written in variables @first_city, @last_city, @date_trip of the controller. Without creating an object in the database. Then pass the values of these variables to another page. It is possible to do that or not?

<%= form_for(@orders) do |f| %>          <p>Выберите маршрут</p>              <%= f.select(:first_city, @city_select, :value => :first_city, prompt: "Откуда")   %>            <%= f.select(:last_city, @city_select, prompt: "Куда")   %>            <%= f.text_field :date_trip  %><br>            <%= f.submit "Дальше", class: "btn" %>      <% end %>  

Unicity on two columns asymmetrically

Posted: 09 May 2016 04:09 AM PDT

This is my table Friendship(user_id1:integer, user_id2:integer)

I want to add a constraint to the database so that a couple of user_id will be rejected if its symetric already exists.

For example, if I already have the couple (42, 17) in the db, I don't want to be able to save (17, 42)

I'm using rails with postgresql.

Print the radio button value in next page in ruby

Posted: 09 May 2016 03:40 AM PDT

Hi I am using 2 radio buttons:

<input type="radio" id="radio0" name="answer[16]" value="Domestic" checked>  <label for="radio0">Domestic</label>    <input type="radio" id="radio1" name="answer[16]" value="International">  <label for="radio1">International</label>  

I want to print these selected radio button value in the next page like :

Usage of Documents: Domestic

any idea how to implement this in ruby?

I have seen this eg in stackoverflow. But getting little bit confused as how to implement in my code: Discussion of the stackoverflow is below: To Get the radio button value in ruby on rails

<div id = "option-1">    <%= radio_button_tag "answer", "#{@ans.id}ans1"%><%= @ans.ans1 %>  </div>    <%= f.radio_button :answer, "#{@ans.id}ans1" %>   

Cannot validate empty nested fields

Posted: 09 May 2016 03:39 AM PDT

I have a nested form for creating members inside an enrollment

class Enrollment < ActiveRecord::Base    has_many :atendees, dependent: :destroy    accepts_nested_attributes_for :atendees, reject_if: :all_blank, allow_destroy: true  end  

and validations on Member model.

If I submit the enrollment form with all blank member fields, the enrollment saves successfully with an empty members array.

If I input any member field and submit it, member model validations take action.

Any ideas why this is happening?

I also tried with checking only one column:

  accepts_nested_attributes_for :atendees, , reject_if: proc { |attributes| attributes['first_name'].blank? }, allow_destroy: true  

How should I implement a searchable model with no table in Rails 4?

Posted: 09 May 2016 03:22 AM PDT

I have an Item model that should behave in a similar way to an ActiveRecord object: it's a collection of records with an id and several columns, which I should be able to search. However, the data is static, and will be imported from a file downloaded from the web, so there is no need to store it in the database (I could, but it seems very inefficient, there's only 200 records or so). Furthermore, I need to establish associations with ActiveRecord models.

So the main question is: what would be the best way to implement this design-wise?

So far, I've found that I can do this

class Item    include ActiveModel::Model      attr_accessor :id, :name, :description, ...  end  

which allows me to do some familiar things like creating objects and validation, but does not allow me to search, so I would have to do that manually. In fact, I would still need a place to store the collection (maybe a class variable or an in-memory store such as Redis?).

Any help is appreciated.

Rails: Puma server 3 not showing database queries in development

Posted: 09 May 2016 05:43 AM PDT

I upgraded Puma to version 3. When I start the development server (rails s -b0.0.0.0), the console only shows the requests, not the actual database queries as before (version <= 3). I couldn't find an option for it.

How can I see the database queries in the development console?

Thanks in advance!

No comments:

Post a Comment