Sunday, July 24, 2016

Rails 4 Join query through has_and_belongs_to_many relationship | Fixed issues

Rails 4 Join query through has_and_belongs_to_many relationship | Fixed issues


Rails 4 Join query through has_and_belongs_to_many relationship

Posted: 24 Jul 2016 08:20 AM PDT

I have a two models, posts and tags, with a many-to-many relationship between them. I have implemented this relationship with a posts_tags table with is formed of posts.post_id and tags.tag_id.

I'm trying to get an active record object of all posts with a certain tag. I have this working with the code:

posts_i_want = []  all = Post.all  all.each do |x|      x.tags.each do |y|          if y.tag == params[:tag]              posts_i_want.push(x.id)          end      end  end  @posts = Post.where(id: posts_i_want)  

But from reading on the subject it seems there is a much better way to do it. Something similar to:

@posts = Post.joins("INNER JOIN posts_tags ON posts.post_id = posts_tags.post_id INNER JOIN tags ON posts_tags.tag_id = tags.tag_id WHERE tags.tag = #{params[:tag]}")  

or

@posts = Post.joins(posts_tags: :tags).where(tag: params[:tag])  

but i was unsuccessful in getting the proper way to work. I'm hoping someone experienced with ruby on rails can suggest what the solution might look like. Thanks!

p.s. using postgresql

Rails Admin: Integration Tests, How to get the named paths for models

Posted: 24 Jul 2016 08:19 AM PDT

In my rails app, I'm using rails_admin and I need to integration test it. I'm using capybara and minitest for integration testing. After clicking link in dashboard, I need to check the path of the current page with expected path.

I want to use named routes which rails_admin provides. I tried:

assert_equal page.current_url, app.rails_admin.dashboard_url  

This gives correct url in console but doesn't work in integration test. What am I missing here.

Thanks in advance,

Call custom controller action from view when I click on a button Rails

Posted: 24 Jul 2016 08:24 AM PDT

I'm struggling with a simple action call in rails and i cannot find what is wrong and why many solutions don't work in my case. I mention that i'm a new guy to rails, coming from Java world.

The problem is like that:
I want to have a button in my view which points to a controller action, an action that changes a column in a table.

routes.rb

post 'punch/userout' => 'punch#userout', :as => :userout

view: punch\out.erb

 <%= link_to('Out', userout_path, method: :post)  %>  

controller: punch_controller.rb

def userout   if current_user     @user = current_user     @user.update_attributes(:punched_in => false)   else     redirect_to new_user_session_path, notice: 'You are not logged in.'   end  end  

And for info: one punch belongs_to :user and users has_many :punches

I have a column in users table that says punched_in: true/false, and I only want that column to be set at false when I click on the link/button from view.

I have tried many solution, with link_to, button_to, different routes etc. In this case, I get this error:

The action 'userout' could not be found for PunchController

In other cases, my button worked but cannot reach the action that I want.

Thanks!

unable to refactor code rails 4 query

Posted: 24 Jul 2016 08:11 AM PDT

Scenario is, I want to get all timeslots for 2 cases.

  1. if doorman is true the query will be same

  2. if doorman is false then need to add a parameter in the query

So, its the same query almost that will work for both cases with little modification.

Here is the query and code:

def self.latest_pickup_date current_zone,doorman      if doorman        latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone).order(:slot_date).last      else        latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone, doorman_type: "none").order(:slot_date).last      end      latest_timeslot.nil? ? Date.current : latest_timeslot.slot_date    end  

I would like to refactor my code and the query in a way to use the approach of DRY.

I do not want to write these queries twice in both cases. I need a better solution using code practices. Or if I am doing this right way, you can advice as well.

Plus need good professional code practices and code refactoring as well if anyone can help with.

Renaming my file to .js.erb allows me to write erb inside javascript but not javascript inside erb

Posted: 24 Jul 2016 08:25 AM PDT

I am using chessboard-0.3.0.js on a rails application. Because of the rails asset pipeline thing, I have had to edit every part of the js code that renders an image, Pieces for example. Line 445 of chessboard.js says

cfg.pieceTheme =  'img/chesspieces/wikipedia/{piece}.png'  

which of course would pose a problem for rails, so I had renamed chessboard with the .erb extension and changed that line to

cfg.pieceTheme =  <%= asset_path('chesspieces/wikipedia/{piece}.png') %>   

after putting all the required images in the assets/images folder.

My problem here is that the images still does not get rendered, I guessed its because of the way {piece}.png is placed in that line, thats basically js inside a rails helper, right? And I think that is why my images do not get rendered. Of course, I could read the whole 'almost 2000' lines of code and try to figure out a way to access each images one after the other, but I could break something else along the way, 2k lines isn't fun to manage for a beginner like myself.

Is there a way to fix this without rewriting the better part of the code??

Cannot find simplecov executable

Posted: 24 Jul 2016 06:51 AM PDT

My understanding is that RubyMine is set up to work with SimpleCov "out of the box". However, whenever I press the "test with coverage" button in RubyMine, I get the following:

RubyMine error message

This is happening for all of my projects. I do have multiple versions of Ruby installed on my mac, but RubyMine is using the correct version (2.2.0-p0). Additionally, ruby -v gives:

ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin15]  

And running gem list for this shows that both simplecov (0.12.0) and simplecov-html (0.10.0) are installed.

When I run rake test in my project directory, the coverage folder is generated, and I can view the coverage reports just fine.

How can I get this integrated with RubyMine so that I can see the coverage reports in-app?

How to automatically pick up current date and time in rails

Posted: 24 Jul 2016 07:45 AM PDT

I have an model wherein i am collecting some data from the form. along with this data i need to automatically log in current data and time when a post request is made.

How can i get current date and time. currently I am able to get current date and time as string type in rails using strftime function.I need the data identical to how it is stored in created and updated timestamps.

Multiple Select box with values pre selected in Rails

Posted: 24 Jul 2016 07:24 AM PDT

Ive been working on implementing acts-as-taggable-on and select2 to get a tagging system similar to here on stackoverflow. I finally got everything to work but there is two issues I can figure out.

  1. How to have tags already saved pre-populated
  2. When I first load the page it doesn't apply the select2 javascript on the initial load but if I refresh the page it formats it correctly with the select2 javascript. (using coffee so might switch to regular javascript)

Heres the two chunks of code that apply:

$(document).on 'ready page:load', ->      $("select#cuisine-select").select2({          tags: true,          tokenSeparators: [',', ' ']          placeholder: 'Select Cuisine'          allowClear: true      });  

The form code:

<div class="fields">      <%= f.label :cuisine_list, "Cuisines (separated by commas)" %>      <%= f.collection_select :cuisine_list, Recipe.cuisine_counts, :id, :name, {},                      { multiple: true, id: "cuisine-select", :style => "width:300px"} %>  </div>  

EDIT: Solved part of this but now when I load the edit it loads correctly but when I update it updates with the ids and not the name. This is what I changed it to:

<div class="fields">      <%= f.label :cuisine_list, "Cuisines (separated by commas)" %>      <%= f.collection_select :cuisine_list, Recipe.cuisine_counts, :id, :name, {:selected => recipe.cuisine_counts.map(&:id)},                          { multiple: true, id: "cuisine-select", :style => "width:300px"} %>  </div>  

Also I changed the page:load to turbolinks:load and that seems to have fixed the problem with it not loading on the initial visit.

How to design structure of database for auto renewal weekly subscription in rails

Posted: 24 Jul 2016 06:15 AM PDT

First thanks for read my question In Rails Application i have one model for subscription and one for weekly_subscription_schedule which manage auto renewal plan in this subscription model user can pause and resume subscription also

subscription model contain this attribute

1.product_id # integer  2.user_id #integer  3.subscription_status #boolean   4.subscription_date #date  

subscription_schedule

1.subscription_id  2.weekly_subsciption_status  3.subscription_date  

I come with this model but don't know how to manage it ,please guys suggest me proper design so i can manage weekly subscription in rails application

Thanks

How can I get last ActiveRecord query data?

Posted: 24 Jul 2016 06:36 AM PDT

I'm new to Ruby on Rails, so you forgive myself if the question is silly ...

I have a table and two forms, the first form is to filter (through checkboxes) and the second one is to search into the table.

What I would like is to search into the table with the filters already applied. I do not really know to do... how I can access from the controller search method to "already filtered" data.

Source code:

prices_controller.rb

def filter()   @prices = Price.where(date: Date.today).order(price: :asc)    if params[:filter1] != nil       @prices = @prices.where('filter1_field IN (?)', params[:filter1])    end    if params[:filter2] != nil       @prices = @prices.where('filter2_field IN (?)', params[:filter2])    end    respond_to do |format|      format.js    end  end    def search()    # Here I would like to use filtered prices, not all prices    @prices = Price.where(date: Date.today).order(price: :asc)    if params[:search] != nil       @prices = @prices.where('name LIKE ?', "%#{params[:search]}%")    end  end   

It works, but I am not using filtered values... Are there any way to save the last query or something like that. I try to return to the search method the ActiveRecord::Relation but method where does not exists in this class. Other alternative is use the same form to filtering and searching.

I accept any kind of recommendation.

Thanks a lot.

In Rails, onbeforeunload not working consistently for Chrome browser

Posted: 24 Jul 2016 05:58 AM PDT

I'm trying to get onbeforeunload to work consistently on my page that has a form users are filling out. I'm expecting the following:

  • When I click a link to another page, it would prompt the user
  • When I refresh the page, it would prompt the user

I'm currently testing under Google Chrome, and I'm using the following now - though I've tried some variations.

<script>      $(document).on('ready page:load', function () {      $(window).on('beforeunload', function() {        return "You should keep this page open.";      });    });    </script>  

I've been able to get the prompt to show up at times but not consistently. I've thought this might point to a conflict with the code above and turbolinks. But haven't been able to find out a fix to get the expected results mentioned above.

rails cant create an object

Posted: 24 Jul 2016 05:08 AM PDT

So I am making a colors palette manager and both tables requested on the form are nested and properly related(I would like to also point out that I am a rookie to rails)

This whole code was working perfectly fine when in line 4 was requesting links instead of just the names and suddenly wont work anymore, thank you for the help in advance

<div class='nav_bar'>#</div>      <% if @projects %>          <% @projects.each do |project| %>              <li><div class='container'><h1><%= project.name project_path(:id => project.id) %></h1>                  <ul>                      <%= form_for project do %>                      <%= fields_for :palette, project.palette do |palette| %>                          <%= palette.label 'background_dark_color' %>:                        <%= palette.text_field :background_dark_color, placeholder: '@palette.background_dark_color' %><br/>                          <%= palette.label 'background_light_color' %>:                        <%= palette.text_field :background_light_color, placeholder: "@palette.background_light_color" %><br/>                          <%= palette.label 'dark_color1' %>:                        <%= palette.text_field :dark_color1, placeholder: "@palette.dark_color1" %><br/>                          <%= palette.label 'dark_color2' %>:                        <%= palette.text_field :dark_color2, placeholder: "@palette.dark_color2" %><br/>                          <%= palette.label 'light_color1' %>:                        <%= palette.text_field :light_color1, placeholder: "@palette.light_color1" %><br/>                          <%= palette.label 'light_color2' %>:                        <%= palette.text_field :light_color2, placeholder: "@palette.light_color2" %><br/>                          <%= palette.submit %>                          <%= link_to 'Destroy',  project,  method: :delete, data: { confirm: 'Are you sure?' } %>                        <% end %>                      </div>                  </ul>                <% end %></li>          <%end%>      <%end%>      <div class='circle'><%= link_to "+", new_project_path %></div>      <button type="button"><%= link_to "+", new_project_path %></button>  

if statement for a model on a different show page

Posted: 24 Jul 2016 05:17 AM PDT

I have two tables

create_table "book_rooms", force: :cascade do |t|    t.integer  "room"    t.string   "room_number"  end  

and

create_table "rooms", force: :cascade do |t|    t.string   "room_number"  end  

in the rooms show page i want to display 'book_rooms.room_number' with same value with 'rooms.room_number' but I keep getting all book room objects printed out as an array in every room show page

rooms show page

<% @customer = BookRoom.all %>  <% if @customer[0].room_number = @room.room_number %>       <% @customer.each do |c| %>      <%= c.first_name %>    <% end %>  <% end %>    

pls is there something I am not doing right? the if statement is meant to be false if the room_numbers dont tally but they still get printed out regardless! i am stuck

Capybara doesn't find my route in engine

Posted: 24 Jul 2016 08:07 AM PDT

I started a new Rails 5 applications for myself to see how I can modularise an application with engines and simple test purposes. I decided to use Rspec and Capybara for integration tests.

I have a very basic feature rspec:

okinsmen/components/okm_backend/spec/features/humen_spec.rb

require 'rails_helper'    feature "Humen process" do    scenario "go to index page" do      visit '/humen'      expect(page).to have_content("List of humen")    end  end  

That's my route:

okinsmen/components/okm_backend/config/routes.rb

    OkmBackend::Engine.routes.draw do        root 'dashboards#index'        resource :dashboards, only: [:index]        resources :humen      end  

And the result of the command rails app:routes in the terminal:

Prefix Verb URI Pattern  Controller#Action  okm_backend      /okm_backend OkmBackend::Engine    Routes for OkmBackend::Engine:        root GET    /                         okm_backend/dashboards#index       humen GET    /humen(.:format)          okm_backend/humen#index             POST   /humen(.:format)          okm_backend/humen#create  new_human GET    /humen/new(.:format)      okm_backend/humen#new edit_human GET    /humen/:id/edit(.:format) okm_backend/humen#edit       human GET    /humen/:id(.:format)      okm_backend/humen#show             PATCH  /humen/:id(.:format)      okm_backend/humen#update             PUT    /humen/:id(.:format)      okm_backend/humen#update             DELETE /humen/:id(.:format)      okm_backend/humen#destroy  

All looks good, but I get always this error:

1) Humen process go to index page       Failure/Error: visit '/humen'         ActionController::RoutingError:         No route matches [GET] "/humen"  

If I replace visit "/humen" by humen_path, I get this error:

  1) Humen process go to index page       Failure/Error: visit humen_path         NameError:         undefined local variable or method `humen_path' for #<RSpec::ExampleGroups::HumenProcess:0x00000006843ea0>  

To solve this last issue, I have to add this line in my rails_helper.spec:

config.include OkmBackend::Engine.routes.url_helpers  

Now the test pass.

But I can't get the test working with a string URL.

The application can be looked at https://github.com/patdec/okinsmen/tree/engines

It's very basic. Thanks if you can help me.

Rails with Filterrific is not working

Posted: 24 Jul 2016 03:38 AM PDT

I don't get filterrific to work although I feel I am really close to a solution. In my App you can create search requests for products which other people can answer. Now I want to implement filterrific to sort (and later also filter) these search requests. I followed the brilliant documentation on http://filterrific.clearcove.ca/ but I do not find the reason why it is not working in my app. I don't get any errors but whatever I do it is not sorting.

This is my Search model:

    filterrific(        default_filter_params: { sorted_by: 'created_at_desc' },        available_filters: [          :sorted_by,        ]      )    scope :sorted_by, lambda { |sort_option|    # extract the sort direction from the param value.    direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'    case sort_option.to_s    when /^created_at_/      # Simple sort on the created_at column.      # Make sure to include the table name to avoid ambiguous column names.      # Joining on other tables is quite common in Filterrific, and almost      # every ActiveRecord table has a 'created_at' column.      order("searches.created_at #{ direction }")    else      raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")    end  }      def self.options_for_sorted_by      [        ['Created at (Newest first)', 'created_at_desc'],        ['Created at (Oldest first)', 'created_at_asc']      ]  end    

This is my Search controller:

def index     @filterrific = initialize_filterrific(        Search,        params[:filterrific],        select_options: {          sorted_by: Search.options_for_sorted_by        },        persistence_id: 'shared_key',        default_filter_params: {},        available_filters: [],    ) or return    @searches = @filterrific.find.paginate(page: params[:page], per_page: 5)      respond_to do |format|      format.html      format.js  end    end  

This is my index.html.erb:

<%= form_for_filterrific @filterrific do |f| %>    <div>      Sorted by      <%= f.select(:sorted_by, @filterrific.select_options[:sorted_by]) %>  </div>  <div>      <%= link_to(        'Reset filters',        reset_filterrific_url,      ) %>    </div>    <%= render_filterrific_spinner %>    <% end %>      <%= render 'searches/search', locals: { searches: @searches } %>  

This is my partial _search.html.erb:

<div id="filterrific_results">  <% @searches.each do |search| %>  <%= time_ago_in_words(search.created_at) %>  ...  <% end %>  </div>    <%= will_paginate @searches %>  

And finally, my index.js.erb:

<% js = escape_javascript(    render(partial: 'searches/search', locals: { searches: @searches })  ) %>  $("#filterrific_results").html("<%= js %>");  

Why I feel close to a solution? A change of the default_filter_params from 'created_at_desc' to 'created_at_asc' is working. And also the option select list is then automatically changing to 'created at (Oldest first)'. But when I change the option select nothing is happening except the spinner shows up for a second.

Thank you for any help!

Audit functionality for rails models

Posted: 24 Jul 2016 02:49 AM PDT

I'm trying to implement an audit functionality for some of my rails models and store it on an external "event" database (we chose BigQuery).

Each event should be very basic: before_json, after_json, diff, action, object_id

So, I started building this concern that I am planning on adding to my models:

module Auditable    extend ActiveSupport::Concern      included do        before_destroy {audit(:destroy)}        after_validation on: :update do        audit(:update)      end        after_validation on: :create do        audit(:create)      end        def audit(action)        EventSender.send(before_json, self.to_json, diff, action, self.id)      end    end  end  

The only thing I dont know how to implement is getting the before state of the object so I can populate the relevant fields and the diff between the two states.

Any ideas on how I can do it?

SyntaxError in PostsController#new

Posted: 24 Jul 2016 04:27 AM PDT

C:/Users/Sergey/forum/app/views/posts/_form.html.haml:2: syntax error, unexpected ')' ));}\n#{_hamlout.format_script... ^   C:/Users/Sergey/forum/app/views/posts/_form.html.haml:5: unterminated string meets end of file   C:/Users/Sergey/forum/app/views/posts/_form.html.haml:5: syntax error, unexpected end-of-input, expecting keyword_end  

_form.html.haml:

= simple_form_for @post do |f|  =f.input :title  =f.input :content  =f.submit  

Sudden "file to import not found or unreadable: bootstrap sprockets"

Posted: 24 Jul 2016 02:32 AM PDT

I'm using the c9.io IDE to develop my app. Everything's proceeding normally, then all of a sudden I get this:

enter image description here

Literally out of the blue. I'm suspecting I accidentally pressed some hotkey in the IDE but I can't figure out what.

I now have two files in my css folder:

custom.css.css and custom.css.scss

the former has css styling that produces the error:

/*  Error: File to import not found or unreadable: bootstrap-sprockets.          on line 1 of /home/ubuntu/workspace/app/assets/stylesheets/custom.css.scss    1: @import "bootstrap-sprockets";  2: @import "bootstrap";  3: @import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro);  4: @import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css);  5:   6: /* universal *\/    Backtrace:  /home/ubuntu/workspace/app/assets/stylesheets/custom.css.scss:1  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/import_node.rb:67:in `rescue in import'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/import_node.rb:45:in `import'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/import_node.rb:28:in `imported_file'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/import_node.rb:37:in `css_import?'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:313:in `visit_import'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:36:in `visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:160:in `block in visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/stack.rb:79:in `block in with_base'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/stack.rb:115:in `with_frame'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/stack.rb:79:in `with_base'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:160:in `visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:52:in `block in visit_children'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:52:in `map'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:52:in `visit_children'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:169:in `block in visit_children'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:181:in `with_environment'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:168:in `visit_children'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:36:in `block in visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:188:in `visit_root'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:36:in `visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:159:in `visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:8:in `visit'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/root_node.rb:36:in `css_tree'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/tree/root_node.rb:29:in `render_with_sourcemap'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/engine.rb:381:in `_render_with_sourcemap'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/engine.rb:298:in `render_with_sourcemap'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/plugin/compiler.rb:492:in `update_stylesheet'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/plugin/compiler.rb:215:in `block in update_stylesheets'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/plugin/compiler.rb:209:in `each'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/plugin/compiler.rb:209:in `update_stylesheets'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/plugin.rb:82:in `update_stylesheets'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/exec/sass_scss.rb:340:in `watch_or_update'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/exec/sass_scss.rb:51:in `process_result'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/exec/base.rb:52:in `parse'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/lib/sass/exec/base.rb:19:in `parse!'  /usr/local/rvm/gems/ruby-2.3.0/gems/sass-3.4.22/bin/scss:13:in `<top (required)>'  /usr/local/rvm/gems/ruby-2.3.0/bin/scss:23:in `load'  /usr/local/rvm/gems/ruby-2.3.0/bin/scss:23:in `<main>'  /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `eval'  /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `<main>'  */  body:before {    white-space: pre;    font-family: monospace;    content: "Error: File to import not found or unreadable: bootstrap-sprockets.\A         on line 1 of /home/ubuntu/workspace/app/assets/stylesheets/custom.css.scss\A \A 1: @import \"bootstrap-sprockets\";\A 2: @import \"bootstrap\";\A 3: @import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro);\A 4: @import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css);\A 5: \A 6: /* universal */"; }  

deleting the custom.css.css file removes the error showing up but I'm worried that the error still exists (just doesn't show up).

Should be noted that I never made any changes to my gemfile, any css, any erb files, basically nothing was changed to produce this error. Any ideas?

user.valid_password of devise gem does not work

Posted: 24 Jul 2016 02:26 AM PDT

def create  user_password = params[:session][:password]  user_email = params[:session][:email]  user = user_email.present? && User.find_by(email: user_email)    if user and user.valid_password? user_password    sign_in user    user.generate_authentication_token!    user.save    render json: user, status: 200, location: [:api, user]    else    #render json: { errors: "Invalid email or passwords"}, status: 422    render json: { errors: "Invalid email or passwords"}, status: 422    end  

end

not able to login after user has signed in,it seems the valid_password? method does not encrypt the password in same format as encrypted password stored in database by the devise,any help would be appreciated.

What are the best practices for upgrading rails versions with all the dependencies?

Posted: 24 Jul 2016 12:48 AM PDT

whenever some major rails version bump happens, sometimes its real pain to upgrade existing apps for rails (4.x, 5.x etc), given there are plenty of gems which might depend on older versions of rails (ActiveRecord, ActionController, ActiveModel, etc.). And those dependent gems sometimes takes too much time to be upgrade (either not maintained, less active or unavailability of core maintainer team, even for expecting Pull Requests). What is the solution which people around follows for the same?

One workflow which people suggest is fork all the dependent gems and then change whatever you like and keep updating them from their respective master/main branches. I would love to hear what people follow in their workflow.

ActionView::Template::Error (undefined method `model_name' for {:url=>"/photos/100/comments/309/cflags"}:Hash)

Posted: 24 Jul 2016 01:27 AM PDT

I have a very basic Photo and Comment model that works and then I have a built a Cflag model that is used to flag comments. I am getting the following error from Heroku log when I visit the photos/show.html.erb view.

ActionView::Template::Error (undefined method `model_name' for > {:url=>"/photos/100/comments/309/cflags"}:Hash)

Show:

photos/show.html.erb  .  <% @photo.comments.each do |comment| %>    <%= form_for([comment, url: photo_comment_cflags_path(@photo, comment)]) do |f| %>      <%= f.hidden_field :user_id, value: current_user.id %>      <%= f.submit "Report Inappropiate" %>    <% end %>  <% end %>   

Routes:

resources :photos do    resources :comments do      resources :cflags    end  end  

Rails routes:

    photo_comment_cflags GET        /photos/:photo_id/comments/:comment_id/cflags(.:format)          cflags#index                           POST       /photos/:photo_id/comments/:comment_id/cflags(.:format)          cflags#create   new_photo_comment_cflag GET        /photos/:photo_id/comments/:comment_id/cflags/new(.:format)      cflags#new  edit_photo_comment_cflag GET        /photos/:photo_id/comments/:comment_id/cflags/:id/edit(.:format) cflags#edit       photo_comment_cflag GET        /photos/:photo_id/comments/:comment_id/cflags/:id(.:format)      cflags#show                           PATCH      /photos/:photo_id/comments/:comment_id/cflags/:id(.:format)      cflags#update                           PUT        /photos/:photo_id/comments/:comment_id/cflags/:id(.:format)      cflags#update                           DELETE     /photos/:photo_id/comments/:comment_id/cflags/:id(.:format)      cflags#destroy  PhotosController  def show    @photo = Photo.approved.find(params[:id])  end  

Cflags controller:

class CflagsController < ApplicationController  before_action :logged_in_user    def new  end    def create    @comment = Comment.find(params[:comment_id])    @cflag = @comment.cflags.build(cflag_params)      if @cflag.save        if @comment.cflags_count > 1          @comment.update_attribute(:approved, false)            flash[:success] = "Flag created! Comment ##{@comment.id} has been removed for review. Thank you for your feedback"          redirect_to :back        else              flash[:success] = "Flag created! Thank you for your feedback"          redirect_to :back        end      else        redirect_to :back, notice: @cflag.errors.full_messages        end        end          private       def cflag_params        params.require(:cflag).permit(:user_id, :comment_id).merge(user_id: current_user.id)      end  end  

Comments Controller:

def create     @photo = Photo.find(params[:photo_id])     @comment = @photo.comments.build(comment_params)     @comment.save     respond_to do |format|       format.html { redirect_to :back }       format.js      end   end     

Cflag Model:

class Cflag < ActiveRecord::Base    belongs_to :comment, counter_cache: true    belongs_to :user, counter_cache: true    validates :user_id, presence: true     validates :comment_id, presence: true    validates :user_id, uniqueness: {       scope: [:comment_id],      message: 'You can only flag a comment once. Thank you for your feedback.'    }    default_scope -> { order(created_at: :desc) }  end  

Schema:

create_table "cflags", force: :cascade do |t|    t.integer  "comment_id"    t.integer  "user_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    add_index "cflags", ["comment_id"], name: "index_cflags_on_comment_id"  add_index "cflags", ["user_id"], name: "index_cflags_on_user_id"  

Error at the time of installing any rvm '__rvm_make -j4'

Posted: 23 Jul 2016 09:59 PM PDT

I am getting the error whenever I am trying to install any rvm like 1.8.7 / 1.9.3 / 2.2.0 Etc

    Error running '__rvm_make -j4',  showing last 15 lines of /usr/local/rvm/log/1469335754_ruby-1.8.7-p374/make.log    (char *(*)())d2i_X509_REVOKED, (char *)rev)    ^  ossl_x509revoked.c:64:17: note: in expansion of macro 'X509_REVOKED_dup'       if (!(new = X509_REVOKED_dup(rev))) {                   ^  In file included from /usr/include/openssl/asn1_mac.h:62:0,                   from ossl.h:57,                   from ossl_x509revoked.c:11:  /usr/include/openssl/asn1.h:964:7: note: expected 'void * (*)(void **, const unsigned char **, long int)' but argument is of type 'char * (*)()'   void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x);         ^  make[1]: Leaving directory '/usr/local/rvm/src/ruby-1.8.7-p374/ext/openssl'  Makefile:293: recipe for target 'all' failed  make: *** [all] Error 1  +++ return 2  There has been an error while running make. Halting the installation.    To proceed rvm requires a ruby-1.8.7-p374 compatible ruby is installed.  We attempted to install it automatically but it failed with status 2.  Please install it manually (or a compatible alternative) to proceed.  

Getting Error in Kali sana Debian OS

Filter result drop down menu not working with Rails Bootstrap Forms GEM

Posted: 23 Jul 2016 10:03 PM PDT

I am doing this to improve my RoR skills. I am trying to style a form that I have created. This is my original code for the form.

<%= form_tag('/quotation/tints/generate') do %>      <%= label :manufacturer_id, 'Manufacturer' %>      <div class="field">          <%= collection_select(:tint, :manufacturer_id, Manufacturer.order(:name), :id, :name, {:prompt => "Select Manufacturer" }) %>       </div>        Model:      <div class="field">          <%= grouped_collection_select(:tint, :model_id, Manufacturer.order(:name), :models, :name, :id, :name, {:prompt => "Select Model"}) %>       </div>        <%= label :price_front, 'Front Tint' %>      <div class="field">          <%= collection_select(:price, :price_front, Price.where('catogery_id' => "1").order(:name), :id, :name, {:prompt => "Select Front Tint"}) %>       </div>        <%= label :price_rear, 'Size and Back Tint' %>      <div class="field">          <%= collection_select(:price, :price_rear, Price.where('catogery_id' => "1").order(:name), :id, :name, {:prompt => "Select Side & Rear Tint"}) %>       </div>      <div class="form-group">          <%= submit_tag 'Submit', class: "button btn btn-primary" %>      </div>  <% end %>  

User has to select Manufacturer first in order to select the Model. The Model will be filtered based on the Manufacturer. This is the script that I use to active the action. It works perfectly.

jQuery ->      $('#tint_model_id').parent().hide()      models = $('#tint_model_id').html()      $('#tint_manufacturer_id').change ->          manufacturer = $('#tint_manufacturer_id :selected').text()          options = $(models).filter("optgroup[label='#{manufacturer}']").html()          if options              $('#tint_model_id').html(options)              $('#tint_model_id').parent().show()          else              $('#tint_model_id').empty()              $('#tint_model_id').parent().hide()  

Now, I am trying to style the form and dropdown menu. I am using bootstrap_form gem to make my life easier. In order to use the gem, I have to change the form to work with the gem, I changed my code of the form to the code below.

<%= bootstrap_form_tag url: '/quotation/tints/generate' do |f| %>      <div class="field">          <%= f.collection_select :manufacturer_id, Manufacturer.order(:name), :id, :name, {:prompt => "Select Manufacturer"} %>       </div>        <div class="field">          <%= f.grouped_collection_select :model_id, Manufacturer.order(:name), :models, :name, :id, :name, {:prompt => "Select Model"} %>       </div>        <div class="field">          <%= f.collection_select :price_front, Price.where('catogery_id' => "1").order(:name), :id, :name, {:prompt => "Select Front Tint"} %>       </div>        <div class="field">          <%= f.collection_select :price_rear, Price.where('catogery_id' => "1").order(:name), :id, :name, {:prompt => "Select Side & Rear Tint"} %>       </div>      <div class="form-group">          <%= submit_tag 'Submit', class: "button btn btn-primary" %>      </div>  <% end %>  

The form looks beautifully and working as in generating a view after it is submitted. However, I found out that the filter option no longer works. User is able to select Model before selecting the Manufacturer. I did try to bundle install and restart my rails server to try to get it work.

My question is does bootstrap_form gem works with the script that filter the model based on the manufacturer? Is there any other way that I can implant my script to work with bootstrap css?

More info: This is what I have for application.js

//= require jquery  //= require jquery.turbolinks  //= require jquery_ujs  //= require_tree .  //= require bootstrap  

I have added a picture below to illustrate what I mean. Before and After

How can Iinstall ruby on rails in ubuntu?

Posted: 24 Jul 2016 05:27 AM PDT

I tried to install ruby on rails and I used 'gem install rails', but I got this:

ERROR:  Loading command: install (LoadError)          cannot load such file -- zlib  ERROR:  While executing gem ... (NoMethodError)          undefined method `invoke_with_build_args' for nil:NilClass  

What am I doing wrong? Or what do I need to do? Can't find help. DO I need to reinstall Ruby? I'm using Ruby2.3 version and ubuntu 16.04. I must say I'm new to ruby on rails, I'm about to learn.

Thanks for your help!

How i can do one switch with link by role, ruby on rails

Posted: 23 Jul 2016 11:42 PM PDT

I 'm new to ROR . I'm trying to make a switch with conditions. Someone can help me with the correct code

<%= link_to "Profile", (user = User.find(1)  case user.role  when "A"  redirect_to(url)  when "B"  redirect_to(url)  when "C"  redirect_to(url)  else  redirect_to(url)  end)%></i>  

NaN in javascript showing up when using a text input field to sum

Posted: 23 Jul 2016 08:30 PM PDT

I need to sum a value with another one that comes from input text.

HTML

<%= f.text_field :hoursclass, id:"txt_hours" %>       

JS

$(function() {    var price = <%= @room.price %>;    var qtdhours =  parseInt($(':input[id="txt_hours"]').val());    var total = qtdhours * <%= @room.price %>      $("#txt_hours").keyup(function() {       $('#reservation_days').text(qtdhours);      $('#reservation_sum').text(total);   });  

$('#reservation_sum').text(total); returns NaN

Tks in advance

command "rails sever" does not work for me

Posted: 23 Jul 2016 08:22 PM PDT

I get this error below. How can I fix the problem?

=> Booting Puma => Rails 5.0.0 application starting in development on http://localhost:3000 => Run rails server -h for more startup options

Exiting  c:/data/rails/books/config/environments/development.rb:1:in <top (required)>':  undefined local variable or method books' for main:Object (NameError)          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0/lib/acti  ve_support/dependencies.rb:293:in require'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0/lib/acti  ve_support/dependencies.rb:293:in block in require'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0/lib/acti  ve_support/dependencies.rb:259:in load_dependency'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0/lib/acti  ve_support/dependencies.rb:293:in require'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/eng  ine.rb:600:in block (2 levels) in <class:Engine>'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/eng  ine.rb:599:in each'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/eng  ine.rb:599:in block in <class:Engine>'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:30:in instance_exec'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:30:in run'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:55:in block in run_initializers'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:228:in block in tsort_each'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:350:in block (2 levels) in e  ach_strongly_connected_component'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:422:in block (2 levels) in e  ach_strongly_connected_component_from'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:431:in each_strongly_connect  ed_component_from'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:421:in block in each_strongl  y_connected_component_from'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:44:in each'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:44:in tsort_each_child'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:415:in call'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:415:in each_strongly_connect  ed_component_from'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:349:in block in each_strongl  y_connected_component'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:in each'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:in call'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:in each_strongly_connect  ed_component'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:226:in tsort_each'          from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:205:in tsort_each'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/ini  tializable.rb:54:in run_initializers'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/app  lication.rb:352:in initialize!'          from c:/data/rails/books/config/environment.rb:5:in <top (required)>'          from c:/data/rails/books/config.ru:3:in require_relative'          from c:/data/rails/books/config.ru:3:in block in <main>'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/builder.  rb:55:in instance_eval'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/builder.  rb:55:in initialize'          from c:/data/rails/books/config.ru:in new'          from c:/data/rails/books/config.ru:in <main>'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/builder.  rb:49:in eval'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/builder.  rb:49:in new_from_string'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/builder.  rb:40:in parse_file'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/server.r  b:318:in build_app_and_options_from_config'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/server.r  b:218:in app'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/server.rb:59:in app'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-2.0.1/lib/rack/server.r  b:353:in wrapped_app'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/server.rb:124:in log_to_stdout'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/server.rb:77:in start'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/commands_tasks.rb:90:in block in server'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/commands_tasks.rb:85:in tap'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/commands_tasks.rb:85:in server'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands/commands_tasks.rb:49:in run_command!'          from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.0/lib/rails/com  mands.rb:18:in <top (required)>'          from bin/rails:4:in require'          from bin/rails:4:in <main>'  

Rails wont render includes

Posted: 23 Jul 2016 06:44 PM PDT

I have a has_many_and_belongs_to relationship between communities and users. Im trying to modify a scaffold for communities to include the nested users collection. But no matter what method i try, it wont render the users to json. Using Rails 4.

Ive tried User.includes(:user).find(1).

Ive tried render :json => @community.to_json(:include => :users) Ive tried render :json => @community.to_json({:include => :users}) Ive tried both above with all permutations of include and user as both plural or singluar

What am I doing wrong?

Code:

class CommunitiesController < ApplicationController    before_action :set_community, only: [:show, :edit, :update, :destroy, :add_user]      def shows      respond_to do |format|        format.json {render :json => @community.to_json(:include => [:users])}      end    end      ...      private      def set_community        @community = Community.includes(:users).find(params[:id])      end        def community_params        params.require(:community).permit(:name, :logo_path)      end  end      class Community < ActiveRecord::Base    validates_presence_of :name      has_and_belongs_to_many :users  end    class User < ActiveRecord::Base    validates :first_name, presence: true    validates :last_name, presence: true    validates :phone_number, presence: true      has_and_belongs_to_many :communities    end  

Factory girl not making attributes correctly

Posted: 23 Jul 2016 06:43 PM PDT

I am writing a controller_spec_test using Rspec on a model called Form. And I use FactoryGirl to generate models. When I run individual tests in form_controller_spec, they all pass. However, when I run the whole file, I see all test are failing and the error msg is ActiveRecord::RecordInvalid: Validation failed: Form type can't be blank.

Here is my forms.rb Factorygirl file, FactoryGirl.define do

  factory :form do      association :user          sequence :form_type do |n|              Form.form_types.values[n]          end      end  end  

Here is my form.rb model file:

class Form < ActiveRecord::Base    belongs_to :user, required: true        enum form_types: { :a => "Form A", :b => "Form B", :c => "Form C", :d => "Form D"}      validates :form_type, presence: true    validates :form_type, uniqueness: {scope: :user_id}    end  

Here is my forms_controller_spec.rb file:

require 'rails_helper'    RSpec.describe FormsController, type: :controller do      login_user        let(:form) {          FactoryGirl.create(:form, user: @current_user)      }        let(:forms) {          FactoryGirl.create_list(:form , 3, user: @current_user)        }        let(:form_attributes) {          FactoryGirl.attributes_for(:form, user: @current_user)      }        describe "GET #index" do          before do              @forms = forms          end            it "loads all of the forms into @forms" do              get :index              expect(assigns(:forms)).to match_array(@forms)          end      end    end  

I do not get that individual tests are passing but the tests are failing when I run the whole file. And I also do not know why form_type is empty.

Understanding sessions and cookies

Posted: 23 Jul 2016 06:38 PM PDT

I'm learning about sessions and cookies (also learning rails), and I came to wonder: why so many people have recommended me to store shopping car values in cookies or sessions if, when the session is over ( user logs out or cleans cookies manually), all the data about the shopping cart cease to exist? I want to remember those selected items, I think that when the connection is over, so is the data! I think I'm misunderstanding something, because I thought that maybe we can store that shopping cart info in a database table, in which the key would be the user_id and it would be persistent.

This may be a silly question, so I'd be very grateful if someone explained to me why,

Thanks!

No comments:

Post a Comment