Wednesday, May 11, 2016

Error RSpec ActionController::UrlGenerationError with Rails | Fixed issues

Error RSpec ActionController::UrlGenerationError with Rails | Fixed issues


Error RSpec ActionController::UrlGenerationError with Rails

Posted: 11 May 2016 07:05 AM PDT

I'm getting an error when trying to test a Rails Controller with RSpec. It's a double nested route and I'm trying to figure out the right syntax but hadn't had many luck yet.

The error that I'm getting is Failure/Error: get :index, {category_id: category.to_param, id: system.to_param}

ActionController::UrlGenerationError:   No route matches {:action=>"index", :category_id=>"220", :controller=>"reviews", :id=>"166"}   # ./spec/controllers/reviews_controller_spec.rb:11:in `block (3 levels) in <top (required)>'  

I've made the same test for the system controller which works fine. The webpage works fine as well. No errors with that (just this error with testing).

Here is what the RSpec test look like:

require 'rails_helper'    RSpec.describe ReviewsController, type: :controller do      let (:category) { create(:category) }    let (:system) { create(:system) }    let (:reviews) { create_list(:review, 3, category: category, system: system) }     describe "GET index" do     it "assigs all reviews to an instance var called @reviews" do      get :index, {category_id: category.to_param, id: system.to_param}      expect(assigns(:reviews)).to eq reviews     end      it "assigns all the reviews to an var called @system" do     get :index, system_id: system.to_param     expect(assigns(:system)).to eq system    end   end     describe "system scope" do    before { create(:review) }      it "only assigns reviews index in the current system" do     get :index, {category_id: category.to_param, id: system.to_param}     expect(assigns(:reviews)).to eq reviews    end   end  end  

This is the Controller that it's testing:

class ReviewsController < ApplicationController      def index     @system = System.find(params[:system_id])     @reviews = @system.reviews      respond_to do |format|     format.html     format.json { render json: { system: @system, reviews: @reviews } }    end     end     def show    @system = System.find(params[:system_id])    @review = @system.reviews   end    end  

And these are the routes:

class ReviewsController < ApplicationController      def index      @system = System.find(params[:system_id])      @reviews = @system.reviews       respond_to do |format|      format.html      format.json { render json: { system: @system, reviews: @reviews } }     end     end     def show     @system = System.find(params[:system_id])     @review = @system.reviews   end    end  

Using Carrierwave to get Fog filename

Posted: 11 May 2016 07:00 AM PDT

I'm consolidating two Carrierwave uploaders into one, so I need to move the generated files over.

For this I need the Fog filenames, but I can't find them in the Uploader instance.

I'm currently using the following pseudocode:

  [Model].find_each do |instance|        old_filename = instance.[old_uploader].[size].store_path.split("/")[0..-2].join("/") + "/" + instance.[old_uploader].[size].path.split("/").last      old_file = directory.files.get(filename)      new_filename = instance.[new_uploader].[size].store_path.split("/")[0..-2].join("/") + "/" + instance.[new_uploader].[size].path.split("/").last      file.copy(directory_name, new_filename)       #file.destroy    end  

But it seems crazy to me that the Fog filename wouldn't be stored in the Uploader instance.

I'm using the Rackspace adapter rather than AWS.

Is there a way of getting the filename without going round the houses?

undefined method `attributes_builder' for Admin:Module

Posted: 11 May 2016 06:57 AM PDT

Trying to open /admin (Administrate gem) and it raise this error:

undefined method `attributes_builder' for Admin:Module  

I get this error after sign in as admin.

Jquery - Identify if radio button value has not changed

Posted: 11 May 2016 07:12 AM PDT

Is it possible to identify if the value of radio button has not changed?

Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:

$('input[type="radio"]').change(function() {      var selected = $('input:checked[type="radio"]').val();      if(selected == 'true') {         $("#submit_button").data("confirm", "foo");      } else if(selected == 'false') {          $('#fee').hide();          $("#submit_button").data("confirm", "bar");      }  

This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?

Ecape only single backslash and leave double backslashes

Posted: 11 May 2016 07:05 AM PDT

I have scenario to escape single backslash in string, but it can also contain double backslashes too.

"<p>&nbsp; \\$%&amp;;&ntilde;&aacute;&lt; &gt;</p>\r\n"  

To

 "<p>&nbsp; \\$%&amp;;&ntilde;&aacute;&lt; &gt;</p>\\r\\n"  

How do I do this in ruby. please note I m keeping the existing double '\' intact.

Thanks

Rails app with puma on Ubuntu server freezes after a while

Posted: 11 May 2016 07:04 AM PDT

I've mounted an Ubuntu Server VM to host my app.

The app works perfectly after I start it. After a while of inactivity (around 5 min with no requests) the app stops responding when I send requests to it. The server logs:

Started GET "/" for 190.104.243.172 at 2016-05-11 13:22:46 +0000  

And nothing more. It should log:

Started GET "/" for 190.104.243.172 at 2016-05-11 13:22:46 +0000  Processing by DashboardController#root as HTML  Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)  Started GET "/users/sign_in" for 190.104.243.172 at 2016-05-11 13:24:16 +0000  ...  

It's like it's not processing the request once it gets it.

This is my puma.rb config file

threads_count = Integer(ENV['MAX_THREADS'] || 16)  threads threads_count, threads_count  workers 1      preload_app!    rackup      DefaultRackup  port        ENV['PORT']     || 3000  environment ENV['RACK_ENV'] || 'development'    on_worker_boot do    ActiveSupport.on_load(:active_record) do      ActiveRecord::Base.establish_connection    end  end    before_fork do    ActiveRecord::Base.connection_pool.disconnect!  end  

If I change the number of workers to 2 for example, the first request after 5 minutes works. If I then wait 5 more minutes, it freezes. So definitely must be something with workers hanging or not loading properly.

Capistrano/Sidekiq task not working

Posted: 11 May 2016 06:29 AM PDT

I am using rails 4.0 and ruby 2.3.

I am using following gems for capscript.

capistrano (3.4.0)  capistrano-bundler (1.1.4)  capistrano-rails (1.1.5)  

I am using capistrano/sidekiq module for running sidekiq related tasks.

When I am running

 cap staging sidekiq:start  

I get the following error:

cap aborted!  SSHKit::Runner::ExecuteError: Exception while executing as      deploy@10.50.11.190: sidekiq exit status: 1  sidekiq stdout: Nothing written  sidekiq stderr: Nothing written    SSHKit::Command::Failed: sidekiq exit status: 1  sidekiq stdout: Nothing written  sidekiq stderr: Nothing written  

Below is the command which failed on running the above task.

cd /opt/optimus_apps/merchant_tracking/current && /usr/bin/env sidekiq --index 0 --pidfile     /opt/optimus_apps/merchant_tracking/shared/server/tmp/pids/sidekiq-0.pid -- environment staging --logfile /opt/optimus_apps/merchant_tracking/shared/server/log/sidekiq.log --config /opt/optimus_apps/merchant_tracking/shared/server/config/sidekiq.yml --daemon  

I tried running the above command directly on the staging server with a small change and it worked. I ran the following command.

 cd /opt/optimus_apps/merchant_tracking/current/server && /usr/bin/env sidekiq --index 0 --pidfile  /opt/optimus_apps/merchant_tracking/shared/server/tmp/pids/sidekiq-0.pid --environment staging --logfile /opt/optimus_apps/merchant_tracking/shared/server/log/sidekiq.log --config /opt/optimus_apps/merchant_tracking/shared/server/config/sidekiq.yml --daemon  

I changed the rails path from

 /opt/optimus_apps/merchant_tracking/current --> /opt/optimus_apps/merchant_tracking/current/server  

The problem is my rails app lies inside current/server folder.

So my question is how can I make sidekiq task to pick current/server folder rather than the current folder?

Thanks in advance.

Modify the lastest posts

Posted: 11 May 2016 06:21 AM PDT

I'm new in rails and I'm trying to build a web app, but I encounter the limits of my abilities. I have a classic app with user who have posts, and to put this post in public, I create a model and a controller Online. That I'm trying to do now, It's to change the boolean :push(from Online) in false if a new Online is created with the same post_id as before. So if I push again my post 2, the previews Online associated with the post 2 will update their :push in false. Well, if you have any ideas about that, let me know ! Thanks

My code =

Controllers:

  • Onlines :

class OnlinesController < ApplicationController    before_action :authenticate_user!    before_action :set_post     before_action :owned_online, only: [:new, :edit, :update]    before_action :set_online        def new       @online = current_user.onlines.build      @online.post_id = @post.id      @online.user_id = current_user.id    end       def create       @online = @post.onlines.create(online_params)      @online.user_id = current_user.id      @online.post_id = @post.id      if @online.save        if @online.portion <= 1            @online.update(push: false)            flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '            redirect_to root_path           else         @online.update(push: true)         @online.update(pushed_at: Time.zone.now)        flash[:success] = 'Votre post est en ligne !'        redirect_to root_path      end      else         render 'new'      end     end       def show           end       def update        if @onlines.update(online_params)        if @online.push == false          if @online.portion <= 1            @online.update(push: false)            flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '            redirect_to root_path           else           @online.update(push: true)                flash[:success] = 'Votre post a bien été pushé !'        redirect_to root_path              end         end      else        @user.errors.full_messages        flash[:error] = @user.errors.full_messages        render :edit      end    end      private     def online_params    params.require(:online).permit(:user_id, :post_id, :prix, :portion, :push, :pushed_at)    end       def owned_online        @post = Post.find(params[:post_id])    unless current_user == @post.user      flash[:alert] = "That post doesn't belong to you!"      redirect_to :back    end  end        def set_post    @post = Post.find_by(params[:post_id])     end         def set_online      @post = Post.find(params[:post_id])    @online = Online.find_by(params[:id])     end     end

Posts :

class PostsController < ApplicationController    before_action :authenticate_user!    before_action :set_post, only: [:show, :edit, :update, :destroy]    before_action :set_online    before_action :owned_post, only: [:edit, :update, :destroy]          # GET /posts    # GET /posts.json    def index          @posts = Post.push_posts     end          # GET /posts/1    # GET /posts/1.json    def show      end      # GET /posts/new    def new      @post = current_user.posts.build    end      # GET /posts/1/edit    def edit    end      # POST /posts    # POST /posts.json    def create      @post = current_user.posts.build(post_params)      respond_to do |format|        if @post.save          format.html { redirect_to @post, notice: 'Post was successfully created.' }          format.json { render :show, status: :created, location: @post }        else          format.html { render :new }          format.json { render json: @post.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /posts/1    # PATCH/PUT /posts/1.json    def update      respond_to do |format|        if @post.update(post_params)          format.html { redirect_to @post, notice: 'Post was successfully updated.' }          format.json { render :show, status: :ok, location: @post }        else          format.html { render :edit }          format.json { render json: @post.errors, status: :unprocessable_entity }        end      end    end      # DELETE /posts/1    # DELETE /posts/1.json    def destroy      @post.destroy      respond_to do |format|        format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }        format.json { head :no_content }      end    end            private      # Use callbacks to share common setup or constraints between actions.      def set_post        @post = Post.find(params[:id])      end                     # Never trust parameters from the scary internet, only allow the white list through.      def post_params        params.require(:post).permit(:user_id, :title, :description, :image, ingredients_attributes: [:id, :name, :_destroy])      end        def owned_post      unless current_user == @post.user      flash[:alert] = "That post doesn't belong to you!"      redirect_to root_path    end  end      def set_online    @onlines = Online.find_by(params[:id])     end     end

Models

  • Online :

class Online < ActiveRecord::Base        belongs_to :post    belongs_to :user          scope :push, ->{ where(push: true).order("pushed_at DESC") }        end

  • Post :

  class Post < ActiveRecord::Base          belongs_to :user    has_many :onlines, dependent: :destroy      scope :push_posts, lambda { joins(:onlines).merge(Online.push) }       has_many :ingredients, dependent: :destroy            accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true      has_many :comments        validates :image, presence: true      has_attached_file :image, styles: { medium: "300x300#"}, default_url: "/images/:style/missing.png"    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end

& finaly, the view to display the index of post :

   <div class="row">  <%- @posts.each do |post|%>  <%- if post.onlines.last.push == true %>  <div class="post">    <div class="form-group text-center">      <h3> <%=post.title%></h3>    </div>         <p> Posted by : <%= link_to post.user.pseudo, profile_path(post.user.pseudo) %>,  <%= time_ago_in_words(post.onlines.last.pushed_at) %> ago </p>        <p><%= post.onlines.last.prix %></p>  <p><%= post.onlines.last.portion %></p>      <div class="image text-center">      <div class="image-border">       <%= link_to (image_tag post.image.url(:medium), class: 'img-responsive'), post_path(post)%>      </div>    </div>          </div>     <% end %>    <%end%>    </div>   </div>   </div>

Rails - Can't create a record that has an attribute with the same name of the class

Posted: 11 May 2016 06:18 AM PDT

I'm having troubles trying to create (or even update) a database record, because both the parent class name and the name of an attribute are equal. I'm using a consolidated database, so I can't alter the tables.

I have a class Period with an attribute 'period'. One period has many tax scales.

#period model  has_many :tax_scales,       foreign_key: 'period',       primary_key: 'period'    #tax_scale model  belongs_to :period,       foreign_key: :period,      primary_key: :period  

So, when I use this in my tax_scale view:

#new.html.haml  = f.label :period  = f.number_field :period  

I get this error:

Period(#97477176) expected, got String(#8598408)

My controller params are:

params.require(:tax_scale).permit(:minimum, :maximum, ..., :period)  

How can I edit (or create) a tax_scale record succesfully?

Business Entity in Rails? Or How to separate that from models?

Posted: 11 May 2016 06:29 AM PDT

I have a User Model and it has a method like checkAge. Now I don't want this in the User model. I want User model to be clean. SO where should I put the checkAge method.

Failed to recognize type of 'location'. It will be treated as String

Posted: 11 May 2016 06:51 AM PDT

I'm trying to use the gem activerecord-postgis-adapter and when i try to execute this code :

require 'active-record'   require 'pg'  require 'active record-postgis-adapter'    class Place < ActiveRecord::Base     record = Place.find(1)     line = record.location     puts line.srid  end  

srid is a method of activerecord-postgis-adapter and here i'm trying to display the srid of my geographical column (location) but the console keeps telling me Failed to recognize type of 'location'. It will be treated as String..

How to edit values from table in place (tried with x-editable)

Posted: 11 May 2016 06:10 AM PDT

I have a team model with fields game1, game2, game3, game4, game5 (all this fields have default value 0). When I display each of them in view I would like to change this default value.

Later when I change this values in last column in my view I will sum all this values.

Question: How should I edit default values and what is the best way to do it?

application.js

//= require editable/rails  

application.css.scss

@import "editable/rails"  

teams.js

$(document).ready(function() {      $('.editable').editable()  });  

teams_controller.rb

class TeamsController < ApplicationController      helper_method :xeditable?        def xeditable? object = nil          current_team.xeditable?      end        def current_team          @team = Team.find(team_params)      end        private        def team_params          params.require(:team).permit(:name, :game1, :game2, :game3, :game4, :game5)      end  end  

teams/index.html.erb

<% @teams.each do |team| %>       <tr>           <td><%= team.name %></td>           <td><%= editable team, :game1 %></td>           <td><%= editable team, :game2 %></td>           <td><%= editable team, :game3 %></td>           <td><%= editable team, :game4 %></td>           <td><%= editable team, :game5 %></td>      </tr>  <% end %>  

NOTE: When I made editable in view like this <%= editable team, :game3 %>, I'm getting error: param is missing or the value is empty: team

How should I make that this editable in place works? Or there is better solution?

link with ruby code and javascript

Posted: 11 May 2016 06:28 AM PDT

I'm building an application using ruby on rails for the backend and js, ajax for the front end. In a html.erb file that I created, to listed all the elements of a certain "event", I implemented some ruby code into the html which it was fine... but I came up with this page that it has been created for someone else in ajax... All I want to do is to put a link that redirects me on anoter page... For my file I used this line of code to redirect me on the page I want

 <a href='/events/<%= event.id %>'>Click for details...</a>  

How can I do the same in the ajax script?

 var $newDiv = $(html);  

I would like to append to this $newDiv the link I showed before or something equivalent... How can I do it?

I hope my question is clear

Désactivate the oldest post

Posted: 11 May 2016 05:34 AM PDT

I'm new in rails and I'm trying to build a web app, but I encounter the limits of my abilities. I have a classic app with user who have posts, and to put this post in public, I create a model and a controller Online. That I'm trying to do now, It's to change the boolean :push(from Online) in false if a new Online is created with the same post_id as before. So if I push again my post 2, the previews Online associated with the post 2 will update their :push in false. Well, if you have any ideas about that, let me know ! Thanks

My code =

Controllers:

  • Onlines :

class OnlinesController < ApplicationController    before_action :authenticate_user!    before_action :set_post     before_action :owned_online, only: [:new, :edit, :update]    before_action :set_online        def new       @online = current_user.onlines.build      @online.post_id = @post.id      @online.user_id = current_user.id    end       def create       @online = @post.onlines.create(online_params)      @online.user_id = current_user.id      @online.post_id = @post.id      if @online.save        if @online.portion <= 1            @online.update(push: false)            flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '            redirect_to root_path           else         @online.update(push: true)         @online.update(pushed_at: Time.zone.now)        flash[:success] = 'Votre post est en ligne !'        redirect_to root_path      end      else         render 'new'      end     end       def show           end       def update        if @onlines.update(online_params)        if @online.push == false          if @online.portion <= 1            @online.update(push: false)            flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '            redirect_to root_path           else           @online.update(push: true)                flash[:success] = 'Votre post a bien été pushé !'        redirect_to root_path              end         end      else        @user.errors.full_messages        flash[:error] = @user.errors.full_messages        render :edit      end    end      private     def online_params    params.require(:online).permit(:user_id, :post_id, :prix, :portion, :push, :pushed_at)    end       def owned_online        @post = Post.find(params[:post_id])    unless current_user == @post.user      flash[:alert] = "That post doesn't belong to you!"      redirect_to :back    end  end        def set_post    @post = Post.find_by(params[:post_id])     end         def set_online      @post = Post.find(params[:post_id])    @online = Online.find_by(params[:id])     end     end

Posts :

class PostsController < ApplicationController    before_action :authenticate_user!    before_action :set_post, only: [:show, :edit, :update, :destroy]    before_action :set_online    before_action :owned_post, only: [:edit, :update, :destroy]          # GET /posts    # GET /posts.json    def index          @posts = Post.push_posts     end          # GET /posts/1    # GET /posts/1.json    def show      end      # GET /posts/new    def new      @post = current_user.posts.build    end      # GET /posts/1/edit    def edit    end      # POST /posts    # POST /posts.json    def create      @post = current_user.posts.build(post_params)      respond_to do |format|        if @post.save          format.html { redirect_to @post, notice: 'Post was successfully created.' }          format.json { render :show, status: :created, location: @post }        else          format.html { render :new }          format.json { render json: @post.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /posts/1    # PATCH/PUT /posts/1.json    def update      respond_to do |format|        if @post.update(post_params)          format.html { redirect_to @post, notice: 'Post was successfully updated.' }          format.json { render :show, status: :ok, location: @post }        else          format.html { render :edit }          format.json { render json: @post.errors, status: :unprocessable_entity }        end      end    end      # DELETE /posts/1    # DELETE /posts/1.json    def destroy      @post.destroy      respond_to do |format|        format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }        format.json { head :no_content }      end    end            private      # Use callbacks to share common setup or constraints between actions.      def set_post        @post = Post.find(params[:id])      end                     # Never trust parameters from the scary internet, only allow the white list through.      def post_params        params.require(:post).permit(:user_id, :title, :description, :image, ingredients_attributes: [:id, :name, :_destroy])      end        def owned_post      unless current_user == @post.user      flash[:alert] = "That post doesn't belong to you!"      redirect_to root_path    end  end      def set_online    @onlines = Online.find_by(params[:id])     end     end

Models

  • Online :

class Online < ActiveRecord::Base        belongs_to :post    belongs_to :user          scope :push, ->{ where(push: true).order("pushed_at DESC") }        end

  • Post :

  class Post < ActiveRecord::Base          belongs_to :user    has_many :onlines, dependent: :destroy      scope :push_posts, lambda { joins(:onlines).merge(Online.push) }       has_many :ingredients, dependent: :destroy            accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true      has_many :comments        validates :image, presence: true      has_attached_file :image, styles: { medium: "300x300#"}, default_url: "/images/:style/missing.png"    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end

& finaly, the view to display the index of post :

   <div class="row">  <%- @posts.each do |post|%>  <%- if post.onlines.last.push == true %>  <div class="post">    <div class="form-group text-center">      <h3> <%=post.title%></h3>    </div>         <p> Posted by : <%= link_to post.user.pseudo, profile_path(post.user.pseudo) %>,  <%= time_ago_in_words(post.onlines.last.pushed_at) %> ago </p>        <p><%= post.onlines.last.prix %></p>  <p><%= post.onlines.last.portion %></p>      <div class="image text-center">      <div class="image-border">       <%= link_to (image_tag post.image.url(:medium), class: 'img-responsive'), post_path(post)%>      </div>    </div>          </div>     <% end %>    <%end%>    </div>   </div>   </div>

Thanks for your times !!

Auth with todoist API: invalid_grant

Posted: 11 May 2016 06:38 AM PDT

I'm adding the ability to post todos to my Todist list via a simple app. At the moment I am getting the response "error"=>"invalid_grant" when exchanging my code for an access_token.

I'm unsure exactly what 'invalid_grant' is referring too in this context. Other answers I find seem to be regarding various Google APIs. The Todoist API documentation makes no mention of it.

The post request for token exchange is:

uri = URI('https://todoist.com/oauth/access_token')  result = Net::HTTP.post_form(uri, client_id: ENV['TODOIST_CLIENT_ID'], client_secret: ENV['TODOIST_CLIENT_SECRET'], code: params[:code])  json_body = JSON.parse(result.body) # <- prints error  

Any help understanding and solving this is much appreciated.

Update

After reading Takahiko Kawasaki's answer, I have updated the request to the following, but have the same error message.

uri = URI('https://todoist.com/oauth/access_token')  data = {    :client_id => ENV['TODOIST_CLIENT_ID'],    :client_secret => ENV['TODOIST_CLIENT_SECRET'],    :code => params[:code],    :grant_type => 'authorization_code',  }  result = Net::HTTP.post_form(uri, data)  json_body = JSON.parse(result.body)  

rails pg_config path not found

Posted: 11 May 2016 05:16 AM PDT

I installed postgresql on my macbook via postgresql Graphical installer (http://www.postgresql.org/download/macosx/). Now I want to configure pg in my rails project but I dont know where can I find pg_conf path.

bundle config build.pg --with-pg-config=<path to pg_config>  

Rails on Nginx + Phusion Passenger: "It looks like Bundler could not find a gem. Maybe you didn't install all the gems that this application needs."

Posted: 11 May 2016 05:48 AM PDT

I have a Rails app running using Nginx and Phusion Passenger. Everything worked fine for many months, but after the last deploy, I got an error "We're sorry, but something went wrong.".

The Nginx log tells this:

[ 2016-05-11 13:28:26.5617 17187/7ff504072700 App/Implementation.cpp:303 ]: Could not spawn process for application /home/a4aa2/rails/current: An error occured while starting up the preloader.    Error ID: 4153f320    Error details saved to: /tmp/passenger-error-VPT6E4.html    Message from application: <p>It looks like Bundler could not find a gem. Maybe you didn't install all the gems that this application needs. To install your gems, please run:</p>      <pre class="commands">bundle install</pre>    <p>If that didn't work, then the problem is probably caused by your application being run under a different environment than it's supposed to. Please check the following:</p>    <ol>    <li>Is this app supposed to be run as the <code>a4aa2</code> user?</li>    <li>Is this app being run on the correct Ruby interpreter? Below you will        see which Ruby interpreter Phusion Passenger attempted to use.</li>  </ol>    <p>-------- The exception is as follows: -------</p>  Could not find mime-types-2.99.1 in any of the sources (Bundler::GemNotFound)  ...etc...  

My gems seem to be all available:

[a4aa2@bellatrix ~]$ cd rails/current/  [a4aa2@bellatrix current]$ bundle  Using rake 10.5.0  Using i18n 0.7.0  Using json 1.8.3  ...etc...  Bundle complete! 91 Gemfile dependencies, 113 gems now installed.  Gems in the groups development and test were not installed.  Bundled gems are installed into ./vendor/bundle.  

I have no idea how to debug this. The only thing I can think of is re-installing phusion passenger and try again.

I'm on a hosted service. Is it possible that there's another Nginx process/installation running that didn't run before, and now things are messed up between those two?

How to only let the author of comments edit, update & destroy them?

Posted: 11 May 2016 05:06 AM PDT

I'm trying to prevent all users being able to edit, update and destroy comments made to posts in my forum. I managed to prevent all users editing the posts, but i can't work out what i need to do to prevent all users editing the comments.

I solved the post issue with this before_action in the post controller:

before_action :post_owner, only: [:edit, :update, :destroy]  

This is my show.html.haml:

#post_content    %h1= @post.title  %p= @post.content    #comments      %h2          = @post.comments.count          Comments      = render @post.comments        - if user_signed_in?            %h3 Reply to thread          = render'comments/form'            %br/          %hr/          %br            - if @post.user_id == current_user.id              = link_to "Edit", edit_post_path(@post), class: "button"              = link_to "Delete", post_path(@post), method: :delete, data: { confirm: "Are you sure you want to do this?"}, class: "button"  

I added a before_action for comments in the post_controller and tried this in the _comment.html.haml:

.comment.clearfix  .content      %p.comment_content= comment.comment      %p.comment_author= comment.user.email    %br/  %br/  %br/  %br/    - if @comment.user_id == current_user.id        = link_to "Edit", edit_post_comment_path(comment.post, comment), class: "button"        = link_to "Delete", [comment.post, comment], method: :delete, data: { confirm: "Are you sure?"}, class: "button"  

However i receive the following error:

undefined method `user_id' for nil:NilClass  

I think this is a simple solution but i'm not that experienced with ruby on rails just yet.

Rails user customised views/templates with Liquid

Posted: 11 May 2016 04:37 AM PDT

I require functionality within a white label application to allow user defined templates. Customers should be able to fully customise their own layouts/views for their sites. Think of functionality similar to Shopify's templating engine.

I have been using the Shopify templating library called Liquid and its working great for something simple like email templates. However, it's becoming a struggle for me to understand how it will work when fully replacing all my .erb files.

Questions:

  • How will I replace Rails view code (link_to, form_for etc.) in Liquid templates"?
  • How can I leverage the Rails routing engine to generate URL's in templates?
  • Do I just create hundreds of custom liquid tags to replace all normal Rails helpers?

I have seen some gems on Github that help integrate liquid with Rails but I would prefer only to rely on the Liquid library.

Cheers

How to search for a nil value using Searchkick?

Posted: 11 May 2016 04:30 AM PDT

In a Rails 4 app, I have related models Applicant and Trademark, with the latter searchable using Searchkick:

class Applicant < ActiveRecord::Base    has_many :trademarks  end    class Trademark < ActiveRecord::Base    belongs_to :applicant    searchkick  end  

I'm trying to find instances of Trademark which do not have an Applicant. Using standard ActiveRecord the below query works, and returns the Trademark without an Applicant:

Trademark.where(applicant: nil).count     (1.7ms)  SELECT COUNT(*) FROM "trademarks" WHERE "trademarks"."applicant_id" IS NULL   => 1   

How can I run the equivalent query with the addition of SearchKick?

# these queries run correctly and show that SearchKick is working  Trademark.search "*" # => 7 records  Trademark.search "*", where: {status: "Removed"} # => 5 records    # When trying to search for applicant == nil, the search fails:    # this returns 7 records, instead of the 1 expected result  Trademark.search "*", where: {applicant: nil}     # this returns 0 records, instead of the 1 expected result  Trademark.search "*", where: {applicant_id: nil}  

How can I use a where clause for a nil value in SearchKick?

RoR HTML template to .docx

Posted: 11 May 2016 07:16 AM PDT

I need to create a .docx file from a HTML template, so I used htmltoword gem.

Usage:

I added the gem (Gemfile):

gem 'htmltoword', '~> 0.5.1' #last version of the gem  

I put a route (route.rb):

get 'preview' => 'foo#preview'  

And in my bar.html.erb I have a link which target's that url:

<%= link_to '.docx', preview_path %>  

Template (preview.docx.erb):

<h1>foobar</h1>  

And in the controller (foos_controller.rb):

class FoosController < ApplicationController    respond_to :docx      #other code      def preview      respond_to do |format|        format.docx do          render docx: 'foobar', filename: 'preview.docx'        end      end    end  end  

However, I'm getting an error:

ActionController::UnknownFormat

How to fix this error?

My config:
RoR v4.2.4
Ruby v2.2.3p173


Also, there is an open github issue for this/similar topic.


Update: as @kajalojha mentioned, respond_with / Class-Level respond_to has been removed to an individual gem, so I installed the responders gem, however, I get the same error.

Is there a different between self and source in Rails Draper::Decorator?

Posted: 11 May 2016 06:10 AM PDT

I'm using Draper::Decorator gem in Ruby On Rails. Is there a different between calling to self or source there?

class MyObjDecorator < Draper::Decorator      def as_json(options={})      ap (self == source)    end      ...  end  

and this is where I call the decorator:

MyObjDecorator.decorate(my_obj).as_json  

My as_json methods prints true, but will this always be true?

AWS Elastic Beanstalk - Passenger Standalone - Rails not setting asset cache headers

Posted: 11 May 2016 04:09 AM PDT

I have a rails application running on AWS EB with passenger standalone. However the asset served doesn't seem to set cache headers. What is the preferred way to do this?

Wrong rails plural when creating a model

Posted: 11 May 2016 04:35 AM PDT

I'm having problems with rails plurals.

I have a model named CompanySkill (which represents the skills owned by a company). When creating the model rails pluralizes it with companies_skill instead of company_skills, therefore when I need to set up the has_many :company_skills association rails doesn't use the model.

What is the correct solution to this problem? What I thought about is to use inflections, but I don't know if it is the right solution and/or there are better solutions.

I'm generating the model from the console:

rails generate model CompanySkill    invoke  active_record    create    db/migrate/20160511111048_create_companies_skill.rb    create    app/models/company_skill.rb    invoke    test_unit    create      test/models/company_skill_test.rb    create      test/fixtures/companies_skill.yml  

Paperclip save image without losing quality

Posted: 11 May 2016 05:46 AM PDT

How to save image and don't lose quality?

in my model

has_attached_file :image, :styles => {:blog_article_main => "940x400#"}  

original image enter image description here and after saveenter image description here it became blurry

bootstrap modal working on one page, not working on another page

Posted: 11 May 2016 05:51 AM PDT

I am working in ruby on rails. Trying to show a modal, which works on another page, but for some reason, same code doesn't show the modal on this page.

So, this is the relevant code in the view file:

<%= javascript_include_tag 'advertisements', 'data-turbolinks-track' => true %>  <%= stylesheet_link_tag    'advertisements', media: 'all', 'data-turbolinks-track' => true %>    <script>    if( window.canRunAds === undefined ){      var p = 24;      console.log(p);      $('#myModal1').modal('show');    }  </script>    <!-- Modal -->  <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">    <div class="modal-dialog" role="document">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>      <h4 class="modal-title" id="myModalLabel">Modal title</h4>        </div>        <div class="modal-body">          ...        </div>        <div class="modal-footer">          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>          <button type="button" class="btn btn-primary">Save changes</button>        </div>      </div>    </div>  </div>  

canRunAds is defined in advertisements.js file. So, if this window doesn't have this variable, it should show the modal. I can see the p value in the js console, so that means javascript is being rendered, somehow modal is not showing.

The same code works in another view file with different id. I tried several things, but couldn't resolve. Any help would be much appreciated. Thanks!

Angular's ngIf statement breaks Capybara test

Posted: 11 May 2016 06:44 AM PDT

My test suite breaks when adding an ngIf statement to a validation tag.

I have a div that shows error messages if a field is invalid. Before, these errors were shown at page load. Now I want to show the errors only after the user has interacted with the input field. Adding an ngIf statement seems perfect for this, but it breaks my test suite.

This is working perfectly:

<div data-ng-messages="userForm.name.$error">      <!-- some input field... -->  </div>  

With this tests get flaky and unreliable.

<div data-ng-messages="userForm.name.$error" data-ng-if="userForm.name.$touched">      <!-- some input field... -->  </div>  

For instance, one of my feature specs tries to fill in a form, submit and reload page to see if the values are persisted. This test is working perfectly without the ngIf statement, but now the page has the old (not updated) values on page reload. The controller method is not even called (for instance UsersController#update if it's an update form).

Gems

  • rspec-rails 3.4.2
  • capybara 2.7.1
  • capybara-webkit 1.11.1
  • database_cleaner 1.5.3

Update

Changing the if statement to userForm.name.$dirty makes tests pass more often... I guess some kind of race condition is introduced here and maybe because $dirty responds a bit faster, that will make tests pass more often...

Messaging Rails controller & view

Posted: 11 May 2016 03:37 AM PDT

Trying to build messaging ability in rails. User to User, all messages(sent and received) appear above the messaging text field and send button (of only the user you are in conversation with)

Currently have the models set up but have been not able to implement the view and controller and started to dig a hole after a couple of days.

Any advise/examples for the view and controller?

contact controller:

class ContactsController < ApplicationController      before_action :contact, only: [:show, :edit, :update, :destroy]    before_action :authenticate_user!        def index      @contacts = current_user.contacts    end      def new      @contact = Contact.new    end      def create      current_user.contacts.create(contact_params)      redirect_to '/contacts'    end      def show    end      def edit    end      def update      @contact.update(contact_params)      redirect_to '/contacts/' + "#{@contact[:id]}"    end        def destroy      @contact.destroy      redirect_to '/contacts'    end      private      def contact_params      params.require(:contact).permit(:firstname, :surname, :email, :phone, :image)    end      def contact      @contact = Contact.find(params[:id])    end      end  

conversation controller:

class ConversationsController < ApplicationController  end  

conversation_users controller:

class ConversationsUsersController < ApplicationController  end  

messages controller:

class MessagesController < ApplicationController    # before_action :message, only: [:show]    before_action :authenticate_user!        def index      @message = Message.new      @messages = current_user.messages    end      def new      # @message = Message.new      # @messages = current_user.messages      # redirect_to '/messages'      # @message = Message.new      end      def create      current_user.messages.create(message_params)      redirect_to '/messages'    end              private      def message_params      params.require(:message).permit(:title, :body, :image)    end      def message      @message = Message.find(params[:id])    end      end  

users controller:

class UsersController < ApplicationController    before_action :authenticate_user!    end  

contact model:

class Contact < ActiveRecord::Base      belongs_to :user      has_attached_file :image, styles: {thumb: "100x100>"}    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/    end  

conversation model:

class Conversation < ActiveRecord::Base      has_many :messages    has_and_belongs_to_many :users  end  

conversation_user model:

class ConversationsUser < ActiveRecord::Base      belongs_to :user    belongs_to :conversation  end  

message model:

class Message < ActiveRecord::Base      belongs_to :user, dependent: :destroy    belongs_to :conversation      has_attached_file :image, styles: {thumb: "100x100>"}    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end  

user model:

class User < ActiveRecord::Base    has_many :messages    has_and_belongs_to_many :conversations        has_many :contacts, dependent: :destroy    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      validates_presence_of :firstname, allow_blank: false    validates_presence_of :surname, allow_blank: false    end  

messages views:

index

<%if user_signed_in? %>    <%= link_to 'Log out', destroy_user_session_path, method: :delete %>  <%end%>      <% if @messages.any? %>      <%= @messages.each do |message| %>      <h3><%= message.title %></h3>        <br />      <%= message.body %>      <br />      <%= image_tag(message.image.url(:thumb)) %>      <%end%>    <%end%>  <br />  <br  />    <%= form_for @message, html: {multipart: true} do |f| %>      <%= f.label :title %>      <%= f.text_field :title %>      <br />      <%= f.label :body %>      <%= f.text_field :body %>      <br />      <%= f.label :image %>      <%= f.file_field :image %>      <br />      <br />      <%= f.submit %>    <% end %>  

schema:

 # These are extensions that must be enabled in order to support this database    enable_extension "plpgsql"      create_table "contacts", force: :cascade do |t|      t.string   "firstname"      t.string   "surname"      t.string   "email"      t.integer  "phone"      t.datetime "created_at",         null: false      t.datetime "updated_at",         null: false      t.string   "image_file_name"      t.string   "image_content_type"      t.integer  "image_file_size"      t.datetime "image_updated_at"      t.integer  "user_id"    end      add_index "contacts", ["user_id"], name: "index_contacts_on_user_id", using: :btree      create_table "conversations", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "conversations_users", force: :cascade do |t|      t.datetime "created_at",      null: false      t.datetime "updated_at",      null: false      t.integer  "conversation_id"      t.integer  "user_id"    end      add_index "conversations_users", ["conversation_id"], name: "index_conversations_users_on_conversation_id", using: :btree    add_index "conversations_users", ["user_id"], name: "index_conversations_users_on_user_id", using: :btree      create_table "messages", force: :cascade do |t|      t.string   "title"      t.text     "body"      t.datetime "created_at",         null: false      t.datetime "updated_at",         null: false      t.integer  "user_id"      t.integer  "conversation_id"      t.string   "image_file_name"      t.string   "image_content_type"      t.integer  "image_file_size"      t.datetime "image_updated_at"    end      add_index "messages", ["conversation_id"], name: "index_messages_on_conversation_id", using: :btree    add_index "messages", ["user_id"], name: "index_messages_on_user_id", using: :btree      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.inet     "current_sign_in_ip"      t.inet     "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "firstname"      t.string   "surname"    end      add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree      add_foreign_key "contacts", "users"    add_foreign_key "conversations_users", "conversations"    add_foreign_key "conversations_users", "users"    add_foreign_key "messages", "conversations"    add_foreign_key "messages", "users"  end  

Rails ransack predicate escape character

Posted: 11 May 2016 05:02 AM PDT

Is there any way to tell ransack which escape character to use?

I created a custom predicate to let the user use asterisk as a wildcard character (instead of %). What this does is to replace any asterisk in the search term with a percent sign.

To let the user search after percent-signs, i want them to be escaped in the search query (except for the actual wildcard asterisks).

As an example i got a user named "us%er_name". Searching for "us%er_na*" should return this user. For this, the query should look like

SELECT * FROM users WHERE username LIKE 'us\%er\_na%' escape '\';  

The escaping and replacement works fine but i don't know how to get "escape '\'" in the query.

A generic solution would be preferred as i don't want to do anything other than to just use my custom predicate.

-e-

In short:

I want to escape a users search term and supply the escape character to the query to get a query like the following when searching after "user%name":

SELECT * FROM users WHERE username LIKE 'user\%name' escape '\';  

Nokogiri add attribute to an html tag without damaging its content

Posted: 11 May 2016 03:28 AM PDT

I'm new to ruby and need to parse html content and update it as required (add an attribute to 'body' tag). I have written the following code

def index      url = "/home/employee/index.html"      doc = Nokogiri::HTML::Document.parse(url)      doc.at_css("body").set_attribute("ng-init", "menu.inspired = 'true'")      File.open('/home/employee/index.txt','w') {|f| doc.write_html_to f}      @content=doc.to_html  end  

The output written in the file is the following

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body ng-init="menu.inspired = 'true'"><p>/home/employee/index.html</p></body></html>  

The output file contains the added attribute, but the content of the html file seems to be overwritten. So I need to figure out where is the mistake I have made.

No comments:

Post a Comment