Sunday, September 25, 2016

How to inherit from Devise Controllers | Fixed issues

How to inherit from Devise Controllers | Fixed issues


How to inherit from Devise Controllers

Posted: 25 Sep 2016 07:29 AM PDT

I have a user model which uses Devise for authentication and also have an administrator model, which also uses Devise. I want administrators to be able to edit users profile via administrators/users/{user.id}/edit, however I want this process to be done through Devise Controllers, therefore I tried to inherit from the Users::RegistrationsController as shown below:

class Administrators::UsersController < Users::RegistrationsController  before_action :set_user, only: [:show,:edit,:update,:destroy]  def index      @users=User.all  end  def show  end    def new      super  end    def update      @user.update(user_params)      redirect_to [:administrators,:users]  end  

but I get the following error:

Could not find devise mapping for path "/administrators/users". This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user]

I tried to change the routes but I still get the same error. Could you please help me?

Why rails mailer renders emails with wrong locale?

Posted: 25 Sep 2016 07:22 AM PDT

The whole application is set to the right locale, while emails render with default :en (English). Any particular reason? .. Even if I move some Devise emails into partials - it starts rendering them with default locale.

Rails 4: Listening for Post Notifications

Posted: 25 Sep 2016 07:21 AM PDT

I've setup a Purchase Model & Purchases Controller to allow users buy Items from my Rails application via PayPal (IPN).
Everything works fine apart from listening for PayPal's IPN answer.

  1. Opening PayPal in new Tab with Button => works
  2. Passing necessary Item information to PayPal => works
  3. Buy Item with PayPal => works
  4. List item as :status => "Completed" in Database => does not work!

User Model:

has_many :purchases  

Purchase Model:

class Purchase < ActiveRecord::Base      belongs_to :tool      belongs_to :user        def paypal_url(return_path)          values = {              business: "merchant@example.com",              cmd: "_xclick",              upload: 1,              invoice: id,              amount: tool.price,              item_name: tool.title,              notify_url: "http://5947992e.ngrok.io/hook" #Test Server          }          "#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query      end  end  

Purchases Controller:

class PurchasesController < ApplicationController      def new          @purchase = Purchase.new(:tool_id => params[:tool_id], :user_id => current_user.id)          if @purchase.save              redirect_to @purchase.paypal_url(purchase_path(@purchase))          else              render :new          end      end        protect_from_forgery except: [:hook]      def hook          params.permit! # Permit all Paypal input params          status = params[:payment_status]          if status == "Completed"              @purchase = Purchase.find(params[:invoice])              @purchase.update_attributes(status: status, transaction_id: params[:txn_id], purchased_at: Time.now)              @purchase.save!              @user = @tool.user              @user.earned_money += @tool.price              @user.save!          end          render nothing: true      end  end  

Routes:

post "/purchases/:id" => "purchases#show"  post "/hook" => "purchases#hook"  

Item Show View (haml):

= link_to image_tag('paypal.png'), new_purchase_path(:tool_id => @tool.id), target: "_blank"  

Thanks in advance for each answer! Please tell me if you need additional information.

Random ActiveRecord with where and excluding certain records

Posted: 25 Sep 2016 07:50 AM PDT

I would like to write a class function for my model that returns one random record that meets my condition and excludes some records. The idea is that I will make a "random articles section."

I would like my function to look like this

Article.randomArticle([1, 5, 10]) # array of article ids to exclude  

Some pseudo code:

ids_to_exclude = [1,2,3]    loop do    returned_article = Article.where(published: true).sample    break unless ids_to_exclude.include?(returned_article.id)  do  

No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}

Posted: 25 Sep 2016 06:47 AM PDT

I have a Rails 5 API-only application that happens to have a static public directory.

I was getting a weird error so I decided to remove everything from public except index.html which has only the following contents:

hello  

I'm running an integration test that looks like this:

require 'rails_helper'    feature 'Books', js: true do    scenario 'list page' do      visit '/'      expect(page).to have_content('hello')    end  end  

When I run my test, I get the following error:

Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"

ActionController::RoutingError: No route matches [GET] "/favicon.ico"

I don't understand why I'm getting this error because nowhere am I telling it I want a favicon.

Doing grep -ir 'favicon' app turns up nothing.

When I visit localhost:3000 in the browser, there are no errors.

Why am I getting this error and how can I fix it?

Rails active record::not found using friendly id and slug recognition

Posted: 25 Sep 2016 07:53 AM PDT

ive set up my rails app to use friendly_id and paperclip and i've added the slug column to the 'designs' database table using a migration. When I create a new design post and upload my image (using paperclip) the slug column is not updated when I check the database and then I get an active record error, saying the following:

enter image description here

Here are my code snippets:

Model:

class Design < ApplicationRecord    attr_accessor :slug    extend FriendlyId    friendly_id :img_name, use: [:slugged, :finders]    has_attached_file :image, styles: {    :thumb    => ['100x100#',  :jpg, :quality => 70],    :preview  => ['480>',      :jpg, :quality => 70],    :large    => ['800>',      :jpg, :quality => 30],    :retina   => ['1200>',     :jpg, :quality => 30]  },  :convert_options => {    :thumb    => '-set colorspace sRGB -strip',    :preview  => '-set colorspace sRGB -strip',    :large    => '-set colorspace sRGB -strip',    :retina   => '-set colorspace sRGB -strip -sharpen 0x0.5'  }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/  end

Controller:

class DesignsController < ApplicationController    before_action :find_design, only: [:show, :edit, :update, :destroy]    before_action :authenticate_user!, except: [:index, :show]      def index      @designs = Design.all.order("created_at desc")    end      def new      @design = Design.new    end      def create      @design = Design.new(design_params)        if @design.save        redirect_to @design, notice: "Hellz yeah, Steve! Your artwork was successfully saved!"      else        render 'new', notice: "Oh no, Steve! I was unable to save your artwork!"      end    end      def show    end      def edit    end      def update      if @design.update design_params        redirect_to @design, notice: "Huzzah! Your artwork was successfully saved!"      else        render 'edit'      end    end      def destroy      @design.destroy      redirect_to designs_path    end      private      def design_params      params.require(:design).permit(:img_name, :slug, :image, :caption)    end      def find_design      @design = Design.friendly.find(params[:id])    end  end

View (#show)

<div id="post_show_content" class="skinny_wrapper wrapper_padding">      <header>          <p class="date"><%= @design.created_at.strftime("%A, %b %d") %></p>          <h1><%= @design.img_name %></h1>          <hr>      </header>            <%= image_tag @design.image.url(:retina), class: "image" %>          <div class="caption">            <p><%= @design.caption %></p>          </div>        <% if user_signed_in? %>        <div id="admin_links">          <%= link_to "Edit Artwork", edit_design_path(@design) %>          <%= link_to "Delete Artwork", design_path(@design), method: :delete, data: {confirm: "Are you sure?" } %>        </div>      <% end %>            </div>

Migration:

class AddSlugToDesigns < ActiveRecord::Migration[5.0]    def change      add_column :designs, :slug, :string      add_index :designs, :slug, unique: true    end  end

Rails ActiveRecord: Saving nested models is rolled back

Posted: 25 Sep 2016 06:16 AM PDT

I've created the simplest example I can think of to demonstrate the issue:

parent.rb

class Parent < ApplicationRecord    has_many :children    accepts_nested_attributes_for :children  end  

child.rb

class Child < ApplicationRecord    belongs_to :parent  end  

Create parent, save, create child, save (works)

Using rails console, creating a new parent, then saving, then building a child from the parent, then saving the parent, works fine:

irb(main):004:0> parent = Parent.new  => #<Parent id: nil, created_at: nil, updated_at: nil>  irb(main):005:0> parent.save     (0.5ms)  BEGIN    SQL (0.4ms)  INSERT INTO `parents` (`created_at`, `updated_at`) VALUES ('2016-09-25 13:05:44', '2016-09-25 13:05:44')     (3.2ms)  COMMIT  => true  irb(main):006:0> parent.children.build  => #<Child id: nil, parent_id: 1, created_at: nil, updated_at: nil>  irb(main):007:0> parent.save     (0.5ms)  BEGIN    Parent Load (0.5ms)  SELECT  `parents`.* FROM `parents` WHERE `parents`.`id` = 1 LIMIT 1    SQL (0.7ms)  INSERT INTO `children` (`parent_id`, `created_at`, `updated_at`) VALUES (1, '2016-09-25 13:05:52', '2016-09-25 13:05:52')     (1.3ms)  COMMIT  => true  

Create parent, create child, save (doesn't work)

However, if I try to create a new parent, then build the child without saving the parent, and finally save the parent at the end, the transaction fails and is rolled back:

irb(main):008:0> parent = Parent.new  => #<Parent id: nil, created_at: nil, updated_at: nil>  irb(main):009:0> parent.children.build  => #<Child id: nil, parent_id: nil, created_at: nil, updated_at: nil>  irb(main):010:0> parent.save     (0.5ms)  BEGIN     (0.4ms)  ROLLBACK  => false  

Can anyone explain why, and how to fix? This is using Rails 5.

Allocate daily sales to date created

Posted: 25 Sep 2016 06:26 AM PDT

Im trying to gather all sales made within a week and put each sale in day made. If Moday was two sales, then Monday => {...}, {...} etc

"Monday" would be ruby's date format.

In my db I have 5 sale objects: Two sales on Monday and two on Tuesday.

Controller:

def daily_customer_sale(created)    date_and_id = Sale.where('created_at >= ?', created).pluck(:created_at, :id)    date_and_id.each do |obj|      yield(obj.first, obj.last)    end  end    def daily_sales(created=nil)    sales_by_date = Hash.new(0)      daily_customer_sale(created) do |date, id|      s_date = date.to_date      sales_by_date[s_date] = Sale.find(id) # Seems to return only one object per day    end      return sales_by_date  end  

For views:

daily_sales(1.week.ago.to_datetime)  

What I get in two dates (correct) in which each data has only one object when it should be two or more per date. Is there something wrong?

RoR display checkbox result

Posted: 25 Sep 2016 05:58 AM PDT

I have a little question, I use simple form for and i would like display a result of a multiple checkboxe in my view. I have a form for create a product and i would like display taht on my view in my index but i have no one idea for do that.

   <%= simple_form_for @publication do |f| %>        <div class="form-inputs">          <%= f.input :as :checkboxes,  collection:[" Application ", "Nature" ,"Design", "Science"],  %>          <div class="form-actions">              <%= f.button :submit , value: "Publier" , class:"btn-btn-sucess" %>  

thx for help.

  • List item

undefined method 'database field' for 'model'

Posted: 25 Sep 2016 06:46 AM PDT

error: thrown from the form

undefined method `profession_id' for #<DirectoryMember:0xa12be40>  

env:

Rails: 5.0.0.1  Ruby: 2.2.4  

form.html.erb

<%= f.collection_select(:profession_id, @professions, :id, :title, {:include_blank => true, :prompt => true}) %>  

routes.rb

resources :directory_members  

directory_members.rb

@professions = Profession.all.order(:title)    def directory_member_params    params.require(:directory_member).permit(    :user_id,     :directory_id,     :name,     :company,     :profession_id,     :address,     :phone,     :facebook,     :video,     :twitter,     :linkedin,     :google_plus,     :youtube    )  end  

schema.rb

create_table "directory_members", force: :cascade do |t|    t.integer  "user_id"    t.integer  "directory_id"    t.string   "name"    t.string   "company"    t.text     "address"    t.string   "phone"    t.string   "facebook"    t.string   "video"    t.string   "twitter"    t.string   "linkedin"    t.string   "google_plus"    t.string   "youtube"    t.datetime "created_at",    null: false    t.datetime "updated_at",    null: false    t.integer  "profession_id"  end  

I have ran rake db:migrate and all seems fine until the is page is rendered. Any clues as to why this is throwing the error would be awesome. Thanks

Rails 4: How to test Controller Action

Posted: 25 Sep 2016 05:55 AM PDT

How do I actually test this Controller Action, I wrote in my PurchasesController:

protect_from_forgery except: [:hook]  def hook      params.permit! # Permit all Paypal input params      status = params[:payment_status]      if status == "Completed"          @purchase = Purchase.find(params[:invoice])          @purchase.update_attributes(status: status, transaction_id: params[:txn_id], purchased_at: Time.now)          @purchase.save!          @user = @tool.user          @user.earned_money += @tool.price          @user.save!      end      render nothing: true  end  

preferably with my Rails Console?

Routes:

post "/purchases/:id" => "purchases#show"  post "/hook" => "purchases#hook"  

Can you configure Rails to warn you when migrations result in data loss?

Posted: 25 Sep 2016 05:44 AM PDT

Things like removing a column result in data loss in Rails. Can you configure it to warn you of these situations (and possibly stop the migration if this happens)? I know Entity Framework does this by default.

Best design for extending class to add ToJson() method

Posted: 25 Sep 2016 05:21 AM PDT

I have a Java class that reads an input stream of "records" and creates a List of Record objects with the record attributes as instance fields. The Record class has a toString() method listing out the values for printing. It implements an Interface which is used by other classes.

As an example, the input stream might be obtained from a File. Assume that I want to build a JavaScript app that would present a File browser, select a file, then use an extension of the above Java class to get List of Record objects from the file returning the objects as an array of Json objects via a toJson() method on the Objects and List. to present in a jQuery DataTable.

Since Json is a particular representation of the data and some other representation might be XML or CSV, what is the best design to provide for these choices without affecting the original interface?

What is the best way to reference the new Java class from jQuery or JavaScript, or from Ruby on Rails, for example. Do I need a servlet, or a web service?

What does the 3rd line of code from the below snippet does?

Posted: 25 Sep 2016 05:13 AM PDT

  def create      chef = Chef.find_by(email: params[:email])      if chef && chef.authenticate(params[:password])        **session[:chef_id] = chef.id**        flash[:success] = "You logged In"        redirect_to recipes_path      else        flash.now[:danger] = "Check your email or password"        render 'new'      end    end  

What does

session[:chef_id] = chef.id  

do? Is that session[:chef_id] a kind of variable or something? To which the id of a chef is assigned? Can I use some other name there?

Illegal key size: possibly you need to install Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files for your JRE

Posted: 25 Sep 2016 04:59 AM PDT

I am using jruby with rails . I have installed JDK7 on my machine. Whenever I start my rails server and try to run my app I am getting error as "Illegal key size: possibly you need to install Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files for your JRE"

I searched on the google and found that I have to download JDK-7 security policy files. So I downloaded these file from here and put these files into my java directory path "C:\Program Files\Java\jdk1.7.0_79\jre\lib\security" . I thought this will resolve my problem but still I am getting same error.

while pasting files in the java's security folder i am getting alert box with information as "you will need to provide administration permission to copy this folder". i cliked on continue button of alert box and file got copied.

I must be missing something.

Please help

Humanizer human validation not working on Devise user seperate actions, Rails 4

Posted: 25 Sep 2016 04:17 AM PDT

I have Rails 4 app with Devise.

Recently, I discovered that for some actions Humanizer function is not working.

Problem: Basically it doesn't check my input regarding security question and allows to move forward with action(But it shouldn't.) No error messages are displayed.

Note: Humanizer works perfectly in user registration process, but doesn't work at all in actions like edit, password recovery etc.

My code:

User.rb:

class User < ActiveRecord::Base      devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable, :lockable, :confirmable    include Humanizer      attr_accessor :bypass_humanizer    require_human_on :create, :unless => :bypass_humanizer      ...    end  

routes.rb

 devise_for :users,  :controllers => {:registrations=> "registrations", :confirmations=> "confirmations", :passwords => "passwords", :sessions => "sessions"}  

Registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController         clear_respond_to         respond_to :json       def sign_up_params      params.require(:user).permit( :email, :password, :country_id, :password_confirmation,:name, :not_a_robot,:current_password,:bypass_humanizer,:role, :humanizer_question_id, :humanizer_answer)    end      def account_update_params      params.require(:user).permit(:name, :email, :password, :country_id,:humanizer_answer, :password_confirmation, :current_password, :not_a_robot, :bypass_humanizer,:confirmation_token, :humanizer_question_id)    end        def destroy      #@p = current_user.id         @user = User.find(current_user.id)       @user.destroy        if @user.destroy          redirect_to root_path, notice: "User deleted."      end      end       private :sign_up_params    private :account_update_params        protected      def update_resource(resource, params)      resource.update_without_password(params)    end    end  

Passwords_controller.rb

class PasswordsController < Devise::PasswordsController        respond_to :json, only: [:create]      skip_before_filter :age_check        def create                user = resource_class.send_reset_password_instructions(resource_params)                  if successfully_sent?(user)                     render json: { data: "something" }, status: 200                else                     render json: { data: "something bad" }, status: 400                end    end       def update      self.resource = resource_class.reset_password_by_token(resource_params)      yield resource if block_given?        if resource.errors.empty?        resource.unlock_access! if unlockable?(resource)        if Devise.sign_in_after_reset_password          flash_message = resource.active_for_authentication? ? :updated : :updated_not_active         # set_flash_message!(:notice, flash_message)          sign_in(resource_name, resource)        else      #    set_flash_message!(:notice, :updated_not_active)        end       # respond_with resource, location: after_resetting_password_path_for(resource)       redirect_to root_path      else        set_minimum_password_length        respond_with resource      end    end    end  

Password recovery form (Humanizer doesn't work):

       <%= form_for(@user,:html => {"data-parsley-validate" => true,:id=>"password-recover-modal",:class=>"password-recover-modal"},:remote=> true,format: :json,as: @user, url: password_path(@user)) do |f| %>            <div class="form-group">               <%= f.email_field :email, autofocus: true ,:class=> "user-input form-control", :id=>"email",:placeholder=>t('email'),required: true%>            </div>                      <div class="question-content" style="position:relative;top:1px;">                          <span class="question"><%= t('question') %>:</span>                               <%=   f.hidden_field :humanizer_question_id %>                           <span class="answer"  >                                   <%= f.label :humanizer_answer, @user.humanizer_question %>                          </span>                                    <div class="form-group" style="margin-bottom:21px;">                                   <span class="question" style="margin-top:8px;"><%= t('answer') %>: *</span>                                        <%= f.text_field :humanizer_answer ,:class=> "form-control",:required => true, :id=>"answer"%>                                 </div>                                          </div>              <%= f.submit t('recover_pass'),:class=> "blue-button btn btn-default"%>       <%end%>  

User registration form(Humanizer works perfectly):

<%= form_for(@user, :html => {:id=>"sign_up_user" ,:class=>"registration-form-modalc","data-parsley-validate" => true},remote: true, format: :json,as: @user, url: registration_path(@user)) do |f| %>                <div class="form-group">                                                     <%= f.text_field :name,:class=> "user-input form-control", :id=>"user-name",autofocus: true ,:placeholder=> t('username_2'),:required => true,:'data-parsley-minlength'=>"3"%>                                                </div>                <div class="form-group">                                          <%= f.password_field :password,:id=>"passwordis",:class=> "user-input form-control", autocomplete: "off" ,:placeholder=> t('new_password'),:required => true,:'data-parsley-minlength'=>"8" %>                                                 </div>                <div class="form-group">                  <%= f.password_field :password_confirmation, :id=>"password-again",:class=> "user-input form-control", autocomplete: "off" ,:'data-parsley-equalto'=>"input#passwordis",:placeholder=> t('new_password_2'),:required => true,:'data-parsley-minlength'=>"8"%>                 <%= f.hidden_field :role, :value => "user"%>                 <%= f.hidden_field :country_id, :value => @location.id%>                 </div>                <div class="form-group">                <%= f.email_field :email ,:class=>"user-input form-control" ,:'data-validatess' => '/blocked/checkemail',:id=>"emailito",:placeholder=> t('email'),:required => true%>                <h3 id="email-taken-message" style="display:none;margin-left:140px;color:red;padding-top:7px;"> <%= t('email_not_available') %> </h3>                                                                                                                              </div>                  <%= f.hidden_field :humanizer_question_id %>                 <div class="question-content" style="position:relative;top:1px;">                 <span class="question"><%= t('question') %>:</span>                 <span class="answer"  >                     <%= f.label :humanizer_answer, @user.humanizer_question %>                 </span>                 <div class="form-group" style="margin-bottom:21px;">                      <span class="question" style="margin-top:8px;"><%= t('answer') %>: *</span>                                                     <%= f.text_field :humanizer_answer ,:class=> "form-control",:required => true, :id=>"answer"%>               </div>                                                   </div>         <%= f.submit t('confirm'),:class=> "blue-button btn btn-default"%>              <%end%>  

Extraction from my logs when I try to use password recovery:

Started POST "/lv/users/password" for 85.254.76.76 at 2016-09-25 14:14:59 +0300  Processing by PasswordsController#create as JS    Parameters: {"utf8"=>"✓", "user"=>{"email"=>"myemail@gmail.com", "humanizer_question_id"=>"1", "humanizer_answer"=>"155"}, "commit"=>"ATGŪT PAROLI", "locale"=>"lv"}    [1m[36mCountry Load (0.4ms)[0m  [1mSELECT  `countries`.* FROM `countries`  WHERE `countries`.`id` = 1 LIMIT 1[0m    [1m[35mRegion Load (0.5ms)[0m  SELECT `regions`.* FROM `regions`  WHERE `regions`.`country_id` = 1    [1m[36mPartner Load (0.4ms)[0m  [1mSELECT  `partners`.* FROM `partners`  WHERE `partners`.`id` = 1 LIMIT 1[0m    [1m[35mUser Load (0.5ms)[0m  SELECT  `users`.* FROM `users`  WHERE `users`.`email` = 'edgars.rworks@gmail.com'  ORDER BY `users`.`id` ASC LIMIT 1    [1m[36mUser Load (247.6ms)[0m  [1mSELECT  `users`.* FROM `users`  WHERE `users`.`reset_password_token` = '8ffe8d2b729cd77dd8f3b3df061e19076b87784edb5d4c10ee1466ee978257f7'  ORDER BY `users`.`id` ASC LIMIT 1[0m    [1m[35m (0.3ms)[0m  BEGIN    [1m[36mSQL (0.5ms)[0m  [1mUPDATE `users` SET `reset_password_sent_at` = '2016-09-25 14:15:00', `reset_password_token` = '8ffe8d2b729cd77dd8f3b3df061e19076b87784edb5d4c10ee1466ee978257f7', `updated_at` = '2016-09-25 14:15:00' WHERE `users`.`id` = 169[0m    [1m[35m (0.3ms)[0m  COMMIT    Rendered devise/mailer/reset_password_instructions.html.erb (4.5ms)    Devise::Mailer#reset_password_instructions: processed outbound mail in 268.7ms    Sent mail to myemail@gmail.com (129.2ms)  Date: Sun, 25 Sep 2016 14:15:00 +0300  From: support@.eu  Reply-To: support@.eu  To: @gmail.com  Message-ID: <57e7b1b4edb10_c48e740a6dc92516@if36.nano.lv.mail>  Subject: Reset password instructions  Mime-Version: 1.0  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: quoted-printable    <html>    <head>      <meta content=3D'text/html; charset=3DUTF-8' http-equiv=3D'Content-Ty=  pe' />    </head>    <body>          <h3> Sveicin=C4=81ti, admins !</h3>      =            <p> K=C4=81ds ir piepras=C4=ABjis saiti, lai main=C4=ABtu paroli. To=   var izdar=C4=ABt, izmantojot zem=C4=81k nor=C4=81d=C4=ABto saiti.</p>      =            <p><a href=3D"http://www.individualki.eu/users/password/edit?reset_p=  assword_token=3Dpq9s-yq74P1mwRFui13L">Main=C4=ABt savu paroli</a></p>           <p></p>          <p>Ja J=C5=ABs neesat piepras=C4=ABjis =C5=A1o, l=C5=ABdzu, ne=C5=86=  emiet v=C4=93r=C4=81 =C5=A1o e-pasta zi=C5=86ojumu.</p>      =           <p></p>         <p>Parole nemain=C4=ABsies, ja J=C5=ABs nespied=C4=ABsiet uz saites a=  ug=C5=A1=C4=81 un nemain=C4=ABsiet to.</p>    </body>  </html>    Completed 200 OK in 1616ms (Views: 0.7ms | ActiveRecord: 260.9ms)  

web-console is not working in all views on Rails 5

Posted: 25 Sep 2016 04:17 AM PDT

To have web-console available on all pages (not just the error pages), I added the following line:

<%= console %>  

in app/views/layouts/application.html.erb

The problem is that the web-console shows up in all pages, except for pages from a certain controller.

When checking the view-page-source, it is also not there (so it is not hidden or something like that).

I'm running in development mode using Ruby 2.3.1 on Rails 5.0

mails from my rails app are getting clipped after installing premailer-gem

Posted: 25 Sep 2016 04:10 AM PDT

My rails app sends out mails every day using the whenever gem. I recently installed premailer-rails gem to separate the styling from html page of the mails.Now all the mails that are sent out say they are clipped and when I click on the "view message" from the inbox I am able to see the mail contents.As far as I know messages in gmail get clipped if they exceed 102kb. Here is my layout for mailer

doctype html  html    head      title example      meta name="viewport" content="width=device-width, initial-scale=1"      = stylesheet_link_tag 'application', media: 'all', 'data-    turbolinks-       track' => true      = javascript_include_tag "application", 'data-turbolinks-track' => true       = render 'layouts/shim'    body      = yield  

Here is my mailer.html.slim

.mail-information-container    .col-md-12.col-sm-12.col-xs-12.heading      h2.pull-left.margin-0        | Daily Report      .col-md-12.col-sm-12.col-xs-12      .intro-container.margin-tp-5        .date           =Time.now.to_date.strftime("%d %B %Y")        .message          | Hello there. Here is today's report on the customer   satisfaction levels        .col-md-4.col-sm-12.col-xs-12     .pulse-info-container.margin-tp-5       table.data-table        tr          th Excellent          td =@pulse_counts[3]        tr          th Good          td =@pulse_counts[2]        tr          th Can Improve          td =@pulse_counts[1]        tr          th Bad          td =@pulse_counts[0]  

I have included style information for only the table to have a border in the css page.Any idea on why the message is getting clipped?

Michael Hartl RoR tutorial, navigation bar chapter 5 not aligning

Posted: 25 Sep 2016 04:30 AM PDT

I'm trying to go through Michael Hartl's (brilliant) Ruby on Rails tutorial, but I have a problem in chapter 5. The navigation bar in the header aligns vertically and aligns to the left, and not horizontally and to the right.

My header (_header.html.erb) looks like this:

<header class="navbar navbar-fixed-top navbar-inverse">    <div class="container">      <%= link_to "sample app", '#', id: "logo" %>      <nav>        <ul class="nav navbar-nav navbar-right">          <li><%= link_to "Home",   '#' %></li>          <li><%= link_to "Help",   '#' %></li>          <li><%= link_to "Log in", '#' %></li>        </ul>      </nav>    </div>  </header>  

and in the Gemfile I have

gem 'rails',                       '5.0.0.1'  gem 'bootstrap-sass',              '3.3.6'  gem 'sass-rails',                  '5.0.6'  

The questions been asked before (like here) but those were with older versions of RoR and of no help to me. Anyone got an idea?

How to get this nested form to create a new object

Posted: 25 Sep 2016 05:03 AM PDT

My Rails 5 application includes two models, Activity and Timeslot.

activity.rb

class Activity < ApplicationRecord    belongs_to :club    has_many :timeslots, :dependent => :destroy    accepts_nested_attributes_for :timeslots    validates :club_id, presence: true    validates :name, presence: true, length: { maximum: 50 }  end  

timeslot.rb

class Timeslot < ApplicationRecord      belongs_to :activity      validates :time_start, presence: true      validates :time_end, presence: true      validates :day, presence: true      #validates :activity_id, presence: true (I realised this was causing one of the errors I had)      default_scope -> { order(day: :asc) }  end  

When I create my activity, I'd also like to create it's first timeslot on the same page, same form.

new.html.erb

<%= form_for(@activity) do |f| %>      <%= render 'shared/error_messages', object: f.object %>      <div class="field">          <%= f.label :name, "Class name" %>*          <%= f.text_field :name, class: 'form-control' %>                <%= f.fields_for :timeslots do |timeslots_form| %>                      <%= timeslots_form.label :time_start, "Start time" %>                      <%= timeslots_form.time_select :time_start %>                        <%= timeslots_form.label :time_end, "End time" %>                      <%= timeslots_form.time_select :time_end %>                        <%= timeslots_form.label :day %>                      <%= timeslots_form.select :day, (0..6).map {|d| [Date::DAYNAMES[d], d]} %>              <% end %>      </div>      <%= f.submit "Create class", class: "btn btn-primary" %>  <% end %>  

My edit/update version of this seems to be working fine.

activities_controller.rb

class ActivitiesController < ApplicationController   ...    def new      @activity = Activity.new      @activity.timeslots.build  end    def create      @activity = current_club.activities.build(activity_params)      #@activity.timeslots.first.activity_id = @activity.id (I thought this might solve the problem, but didn't)      if @activity.save          flash[:success] = "New class created!"          redirect_to activities_path      else          render 'new'      end  end    def edit      @activity = current_club.activities.find_by(id: params[:id])      @activity.timeslots.build  end    def update      @activity = current_club.activities.find_by(id: params[:id])      if @activity.update_attributes(activity_params)          flash[:sucess] = "Class updated!"          redirect_to edit_activity_path(@activity)      else          render 'edit'      end  end  ...    private        def activity_params          params.require(:activity).permit(:name, :active, #active is set to default: true                                           :timeslots_attributes => [:id,                                                                     :time_start,                                                                     :time_end,                                                                     :day,                                                                     :active])      end  end  

But whenever I try to create a new activity I get the error message "Timeslots activities must exist".

I feel it's trying to assign the activity_id for timeslot before the activity is created, but I'm not sure. I've tried many things (some of which I've included in my example in comment form) but am unable to work out why I'm getting this error.

Update: Add error log

Started POST "/activities" for 127.0.0.1 at 2016-09-25 18:04:51 +0700  Processing by ActivitiesController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xp+dBcWC4cjI6FLpIqhU0RzM4ldZ4JpkFLSyAXcmifL73QqWz6R65EHm/Tj7QxlXnWiBA0axjVXvMZHQ+XKA9A==", "activity"=>{"name"=>"Newest class", "timeslots_attributes"=>{"0"=>{"time_start(1i)"=>"2016", "time_start(2i)"=>"9", "time_start(3i)"=>"25", "time_start(4i)"=>"12", "time_start(5i)"=>"00", "time_end(1i)"=>"2016", "time_end(2i)"=>"9", "time_end(3i)"=>"25", "time_end(4i)"=>"13", "time_end(5i)"=>"30", "day"=>"4"}}}, "commit"=>"Create class"}    Club Load (0.2ms)  SELECT  "clubs".* FROM "clubs" WHERE "clubs"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]     (0.1ms)  begin transaction     (0.1ms)  rollback transaction    Rendering activities/new.html.erb within layouts/application    Rendered shared/_error_messages.html.erb (1.5ms)    Rendered activities/new.html.erb within layouts/application (16.9ms)    Rendered layouts/_rails_default.html.erb (58.5ms)    Rendered layouts/_shim.html.erb (0.5ms)    Rendered layouts/_header.html.erb (1.7ms)    Rendered layouts/_footer.html.erb (0.8ms)  Completed 200 OK in 111ms (Views: 93.9ms | ActiveRecord: 0.3ms)  

Updating current_user attribute to true from password update controller action

Posted: 25 Sep 2016 05:00 AM PDT

My Rails 5 App only permits an admin or support user to create a user, when the user is created a password is generated and emailed to the user, on the first user login the app forces them to change the password.

I have a password_updated field in my schema that I want to be filled to true when the password is updated, however I am hitting a wall here, not sure if its coder eye and I just cant see what where im going wrong.

my application controller:

  # Force User To Change Password On First Login    def after_sign_in_path_for(resource)      if current_user.password_updated == "false"        edit_passwords_path      else        authenticated_root_path      end    end  

I have it set up so that if the user tries to skip or jump past the password change they are redirected to the password change.

my passwords controller:

class PasswordsController < ApplicationController    def edit      @user = current_user    end      def update      if current_user.update_with_password(user_params)        current_user.password_updated = "true"        flash[:notice] = 'Your Password Has Been Sucessfully Updated.'        redirect_to authenticated_root_path      else        flash[:error] = 'Oh No! Something Went Wrong, Please Try Again.'        render :edit      end    end      private      def user_params        params.require(:user).permit(:password_updated, :current_password, :password, :password_confirmation)      end    end  

Originally I had the application controller looking at the sign in count, however if the user closed out and waited long enough they could log back in and not have to change the password. I felt this was more of a risk.

Any assistance here would be greatly appreciated.

Using rake db:migrate to create tables in database in mysql. Command appears successful, but databases have no tables

Posted: 25 Sep 2016 03:19 AM PDT

I've been tasked with working on a Ruby on Rails web application and have been given a laptop to work on it. I've managed to grab the source code and get the website up and running on the laptop, however, I can't seem to get rails to communicate fully with mysql.

The issue is that when I try to setup the database using rake commands all appears well until I go and check on the database. I can see that the databases from the database.yml file are created, but the migrated tables are not, even though during the migrate command they appear to be.

I've tried several times recreating the database and re-running the commands, and have even recreated the project, but still have not been able to get the tables to generate. If any other information is needed let me know!

Laptop is running Ubuntu(16.04 LTS)

A full list of used Gems:

  • abstract (1.0.0)
  • actionmailer (3.1.3)
  • actionpack (3.1.3)
  • activemodel (3.1.12, 3.1.3)
  • activerecord (3.1.3)
  • activeresource (3.1.3)
  • activesupport (3.1.12, 3.1.3)
  • ansi (1.4.2, 1.3.0)
  • arel (2.2.3, 2.2.1)
  • Ascii85 (1.0.1)
  • bcrypt (3.1.11)
  • bcrypt-ruby (3.0.1)
  • builder (3.0.4, 3.0.0)
  • bundler (1.0.17)
  • by_star (1.0.1)
  • chronic (0.10.2, 0.6.4)
  • coffee-rails (3.1.1)
  • coffee-script (2.4.1, 2.2.0)
  • coffee-script-source (1.10.0, 1.1.2)
  • css3buttons (1.0.1, 0.9.5)
  • daemon_controller (0.2.6)
  • devise (2.0.0, 1.4.9)
  • erubis (2.7.0)
  • execjs (1.3.0, 1.2.9)
  • fastthread (1.0.7)
  • hike (1.2.3, 1.2.1)
  • i18n (0.6.0, 0.5.0)
  • jquery-rails (1.0.19, 1.0.16)
  • json (1.6.5, 1.6.4)
  • kaminari (0.12.4)
  • libv8 (3.3.10.2 x86_64-linux)
  • mail (2.3.3, 2.3.0)
  • meta_search (1.1.1)
  • mime-types (1.25.1, 1.17.2)
  • minitest (1.6.0)
  • multi_json (1.12.1, 1.0.4)
  • mysql (2.9.1, 2.8.1)
  • mysql2 (0.3.17, 0.3.11, 0.3.7, 0.3.6, 0.2.11)
  • orm_adapter (0.0.7, 0.0.5)
  • pdf-reader (0.10.1)
  • polyamorous (0.5.0)
  • polyglot (0.3.5, 0.3.3)
  • prawn (0.12.0)
  • rack (1.4.7, 1.3.10, 1.3.6)
  • rack-cache (1.1, 1.0.3)
  • rack-mount (0.8.3)
  • rack-ssl (1.3.4, 1.3.2)
  • rack-test (0.6.3, 0.6.1)
  • rails (3.1.3)
  • railties (3.1.3)
  • rake (0.9.2.2, 0.8.7)
  • rdoc (3.12.2, 3.12, 2.5.8)
  • sass (3.1.10)
  • sass-rails (3.1.4)
  • sprockets (2.0.5, 2.0.3)
  • sqlite3 (1.3.4)
  • therubyracer (0.9.8)
  • thor (0.14.6)
  • tilt (1.4.1, 1.3.3)
  • treetop (1.4.15, 1.4.10)
  • ttfunk (1.0.3)
  • turn (0.8.3)
  • tzinfo (0.3.51, 0.3.31)
  • uglifier (1.0.4)
  • warden (1.2.6, 1.0.6)
  • wicked_pdf (0.7.2)

Sum of Table atributes when value is string

Posted: 25 Sep 2016 04:24 AM PDT

I've never come across this before. I'm working with a table attribute whos value is a string, not float/int.

Model.first.amount => "58.00"  

I need to sum up all amount. What I'm used to, with the amount being a float, would be:

Model.all.sum(&:amount) => # total value  

Took a wild guess with:

Model.all.sum(&:amount.to_i) # undefined method `to_i' for :amount:Symbol  

Is there a clean way to sum up the amount? Or convert the database to float?

Rails: unable to deploy to Heroku

Posted: 25 Sep 2016 04:32 AM PDT

UPDATE: Even though I'm completely removing sqlite3gem from my Gemfile and Gemfile.lock, it is still being installed on heroku.

I'm trying to deploy my Rails app to Heroku, and even tho I followed the instructions, I get the infamous sqlite3 error:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  remote:  remote:        /tmp/build_dfa00c2b50bad4da069069454f39d2b2/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160925-219-11i619z.rb extconf.rb  remote:        checking for sqlite3.h... no  remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',  remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'  remote:        and check your shared library search path (the  remote:        location where your sqlite3 shared library is located).  remote:        *** extconf.rb failed ***  remote:        Could not create Makefile due to some reason, probably lack of necessary  remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may  remote:        need configuration options.  remote:  remote:        Provided configuration options:  remote:        --with-opt-dir  remote:        --without-opt-dir  remote:        --with-opt-include  remote:        --without-opt-include=${opt-dir}/include  remote:        --with-opt-lib  remote:        --without-opt-lib=${opt-dir}/lib  remote:        --with-make-prog  remote:        --without-make-prog  remote:        --srcdir=.  remote:        --curdir  remote:        --ruby=/tmp/build_dfa00c2b50bad4da069069454f39d2b2/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)  remote:        --with-sqlite3-dir  remote:        --without-sqlite3-dir  remote:        --with-sqlite3-include  remote:        --without-sqlite3-include=${sqlite3-dir}/include  remote:        --with-sqlite3-lib  remote:        --without-sqlite3-lib=${sqlite3-dir}/lib  remote:  remote:        extconf failed, exit code 1  remote:  remote:        Gem files will remain installed in /tmp/build_dfa00c2b50bad4da069069454f39d2b2/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.  remote:        Results logged to /tmp/build_dfa00c2b50bad4da069069454f39d2b2/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out  remote:        Installing websocket-driver 0.6.4 with native extensions  remote:        Installing rack-test 0.6.3  remote:        Installing nokogiri 1.6.8 with native extensions  remote:        Installing warden 1.2.6  remote:        Installing sprockets 3.7.0  remote:        Installing mime-types 3.1  remote:        Installing coffee-script 2.4.1  remote:        Installing uglifier 3.0.2  remote:        Installing turbolinks 5.0.1  remote:        Installing less 2.6.0  remote:        Installing activesupport 5.0.0.1  remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  remote:        continue.  remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !  remote:  !     Detected sqlite3 gem which is not supported on Heroku.  remote:  !     https://devcenter.heroku.com/articles/sqlite3  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:  remote:  !     Push failed  

The problem is that I have exactly the same Gemfile and Gemfile.lock that I had with a similar project, and this was successfully deployed to Heroku.

Here's my Gemfile:

source 'https://rubygems.org'    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  # Use Puma as the app server  gem 'puma', '~> 3.0'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.2'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks  gem 'turbolinks', '~> 5'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.5'  # Use Redis adapter to run Action Cable in production  # gem 'redis', '~> 3.0'  # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development  gem 'shotgun', '~> 0.9.2'  group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug', platform: :mri  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.    gem 'web-console'    gem 'listen', '~> 3.0.5'    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'    # Use sqlite3 as the database for Active Record    gem 'sqlite3'  end    group :production do    gem 'pg'  end  gem 'twitter-bootstrap-rails', :git => 'git://github.com/seyhunak/twitter-bootstrap-rails.git'  # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  gem 'font-awesome-rails'  gem 'simple_form'  gem 'devise'  

And my Gemfile.lock, which indeed contains the sqlite3 gem:

GIT  remote: git://github.com/seyhunak/twitter-bootstrap-rails.git    revision: d3776ddd0b89d28fdebfd6e1c1541348cc90e5cc    specs:      twitter-bootstrap-rails (3.2.2)        actionpack (>= 3.1)        execjs (>= 2.2.2, >= 2.2)        less-rails (>= 2.5.0)        railties (>= 3.1)    GEM    remote: https://rubygems.org/    specs:      actioncable (5.0.0.1)        actionpack (= 5.0.0.1)        nio4r (~> 1.2)        websocket-driver (~> 0.6.1)      actionmailer (5.0.0.1)        actionpack (= 5.0.0.1)        actionview (= 5.0.0.1)        activejob (= 5.0.0.1)        mail (~> 2.5, >= 2.5.4)        rails-dom-testing (~> 2.0)      actionpack (5.0.0.1)        actionview (= 5.0.0.1)        activesupport (= 5.0.0.1)        rack (~> 2.0)        rack-test (~> 0.6.3)        rails-dom-testing (~> 2.0)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      actionview (5.0.0.1)        activesupport (= 5.0.0.1)        builder (~> 3.1)        erubis (~> 2.7.0)        rails-dom-testing (~> 2.0)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      activejob (5.0.0.1)        activesupport (= 5.0.0.1)        globalid (>= 0.3.6)      activemodel (5.0.0.1)        activesupport (= 5.0.0.1)      activerecord (5.0.0.1)        activemodel (= 5.0.0.1)        activesupport (= 5.0.0.1)        arel (~> 7.0)      activesupport (5.0.0.1)        concurrent-ruby (~> 1.0, >= 1.0.2)        i18n (~> 0.7)        minitest (~> 5.1)        tzinfo (~> 1.1)      arel (7.1.2)      bcrypt (3.1.11)      builder (3.2.2)      byebug (9.0.5)      coffee-rails (4.2.1)        coffee-script (>= 2.2.0)        railties (>= 4.0.0, < 5.2.x)      coffee-script (2.4.1)        coffee-script-source        execjs      coffee-script-source (1.10.0)      commonjs (0.2.7)      concurrent-ruby (1.0.2)      debug_inspector (0.0.2)      devise (4.2.0)        bcrypt (~> 3.0)        orm_adapter (~> 0.1)        railties (>= 4.1.0, < 5.1)        responders        warden (~> 1.2.3)      erubis (2.7.0)      execjs (2.7.0)      ffi (1.9.14)      font-awesome-rails (4.6.3.1)        railties (>= 3.2, < 5.1)      geocoder (1.4.0)      globalid (0.3.7)        activesupport (>= 4.1.0)      gravatarify (3.0.0)      i18n (0.7.0)      jbuilder (2.6.0)        activesupport (>= 3.0.0, < 5.1)        multi_json (~> 1.2)      jquery-rails (4.2.1)        rails-dom-testing (>= 1, < 3)        railties (>= 4.2.0)        thor (>= 0.14, < 2.0)      less (2.6.0)        commonjs (~> 0.2.7)      less-rails (2.7.1)        actionpack (>= 4.0)        less (~> 2.6.0)        sprockets (> 2, < 4)        tilt      listen (3.0.8)        rb-fsevent (~> 0.9, >= 0.9.4)        rb-inotify (~> 0.9, >= 0.9.7)      loofah (2.0.3)        nokogiri (>= 1.5.9)      mail (2.6.4)        mime-types (>= 1.16, < 4)      method_source (0.8.2)      mime-types (3.1)        mime-types-data (~> 3.2015)      mime-types-data (3.2016.0521)      mini_portile2 (2.1.0)      minitest (5.9.0)      multi_json (1.12.1)      nio4r (1.2.1)      nokogiri (1.6.8)        mini_portile2 (~> 2.1.0)        pkg-config (~> 1.1.7)      orm_adapter (0.5.0)      pg (0.19.0)      pkg-config (1.1.7)      puma (3.6.0)      rack (2.0.1)      rack-test (0.6.3)        rack (>= 1.0)      rails (5.0.0.1)        actioncable (= 5.0.0.1)        actionmailer (= 5.0.0.1)        actionpack (= 5.0.0.1)        actionview (= 5.0.0.1)        activejob (= 5.0.0.1)        activemodel (= 5.0.0.1)        activerecord (= 5.0.0.1)        activesupport (= 5.0.0.1)        bundler (>= 1.3.0, < 2.0)        railties (= 5.0.0.1)        sprockets-rails (>= 2.0.0)      rails-dom-testing (2.0.1)        activesupport (>= 4.2.0, < 6.0)        nokogiri (~> 1.6.0)      rails-html-sanitizer (1.0.3)        loofah (~> 2.0)      railties (5.0.0.1)        actionpack (= 5.0.0.1)        activesupport (= 5.0.0.1)        method_source        rake (>= 0.8.7)        thor (>= 0.18.1, < 2.0)      rake (11.3.0)      rb-fsevent (0.9.7)      rb-inotify (0.9.7)        ffi (>= 0.5.0)      responders (2.3.0)        railties (>= 4.2.0, < 5.1)      sass (3.4.22)      sass-rails (5.0.6)        railties (>= 4.0.0, < 6)        sass (~> 3.1)        sprockets (>= 2.8, < 4.0)        sprockets-rails (>= 2.0, < 4.0)        tilt (>= 1.1, < 3)      simple_form (3.3.1)        actionpack (> 4, < 5.1)        activemodel (> 4, < 5.1)      spring (1.7.2)      spring-watcher-listen (2.0.0)        listen (>= 2.7, < 4.0)        spring (~> 1.2)      sprockets (3.7.0)        concurrent-ruby (~> 1.0)        rack (> 1, < 3)      sprockets-rails (3.2.0)        actionpack (>= 4.0)        activesupport (>= 4.0)        sprockets (>= 3.0.0)      sqlite3 (1.3.11)      thor (0.19.1)      thread_safe (0.3.5)      tilt (2.0.5)      turbolinks (5.0.1)        turbolinks-source (~> 5)      turbolinks-source (5.0.0)      tzinfo (1.2.2)        thread_safe (~> 0.1)      uglifier (3.0.2)        execjs (>= 0.3.0, < 3)      warden (1.2.6)        rack (>= 1.0)      web-console (3.3.1)        actionview (>= 5.0)        activemodel (>= 5.0)        debug_inspector        railties (>= 5.0)      websocket-driver (0.6.4)        websocket-extensions (>= 0.1.0)      websocket-extensions (0.1.2)    PLATFORMS    ruby    DEPENDENCIES    byebug    coffee-rails (~> 4.2)    devise    font-awesome-rails    geocoder    gravatarify (~> 3.0.0)    jbuilder (~> 2.5)    jquery-rails    listen (~> 3.0.5)    pg    puma (~> 3.0)    rails (~> 5.0.0, >= 5.0.0.1)    sass-rails (~> 5.0)    simple_form    spring    spring-watcher-listen (~> 2.0.0)    sqlite3    turbolinks (~> 5)    twitter-bootstrap-rails!    tzinfo-data    uglifier (>= 1.3.0)    web-console    BUNDLED WITH     1.13.1  

Thanks for the help!

ActiveAdmin Sortable and Cancancan Ability

Posted: 25 Sep 2016 02:34 AM PDT

I am building a Rails application using ActiveAdmin and ActiveAdmin Sortable gem to change posts order.

I haven't been able to figure out how to authorize this action in my Cancancan ability.rb file.
If I use can :manage, Post it works but I don't want to give all permissions, only some.
Which action should be used in my Ability file to only allow ordering ?

Thanks for your help !

My project:

self.search body Rails

Posted: 25 Sep 2016 04:44 AM PDT

In Rails I'm trying to create an additional Search field for a Articles project in which the 2nd search field searches the Articles Body and not the Title!

Look at the project here https://glacial-island-18918.herokuapp.com/

index.html.erb

    <div id="main">       <%= form_tag articles_path, :method => 'get' do %>        <%= text_field_tag :search, params[:search], class: "form-control", placeholder: "Search Title" %><br><div>         <%= submit_tag "Search", :name => nil, class: "btn btn-success" %>          <% end %>         <%= form_tag articles_path, :method => 'get' do %>        <%= text_field_tag :body, params[:body], class: "form-control", placeholder: "Search Body" %>         <%= submit_tag "Search", :name => nil, class: "btn btn-success" %>          <% end %>  

Article.rb

    def self.search(query)       # where(:title, query) -> This would return an exact match of the query         where("title like ?", "%#{query}%")      end  

ArticlesController.rb

    def index         @articles = Article.all       @markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)        # Adding search feature for Title.        if params[:search]           @articles = Article.search(params[:search]).order("created_at DESC")        else           @articles = Article.all.order('created_at DESC')        end      end  

I've searched through these Stack Posts but can't seem to find an answer(I would have posted more but because my reputation is low I can only post two links.)

Search in Rails ==> But it only talks about getting the search to work correctly for the title, no mention of the body

http://railscasts.com/episodes/111-advanced-search-form/ ==> This one sorta had what I was looking for but this seemed a lot more difficult to me, not simply searching for through another column of the row in the table; searching the Body column instead of Title column.

I've tried adding different methods to the Article.rb model, Articles_controller.rb, but I'm just shooting in the dark; any suggestions Stack family?

Your help would be greatly appreciated! Thanks! =)

Can't Start Rails Server, ActiveAdmin Probably Has Issues

Posted: 25 Sep 2016 01:53 AM PDT

I installed ActiveAdmin to manage the Admin end of my Rails app and everything was absolutely fine till I generated a model for ActiveAdmin. Now the rails server fails to start, even Rake Rollback or rails d active_admin:resource MyModel doesn't work. I am clueless now, might be a simple stupid error but still I can't figure it out, BTW here's the error dump.

/home/ubuntu/workspace/app/admin/products.rb:1:in `<top (required)>': uninitialized constant Products (NameError)          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:216:in `block in load'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/error.rb:41:in `capture'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:216:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:208:in `block in load!'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:208:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:208:in `load!'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin/application.rb:230:in `routes'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-f8926831429f/lib/active_admin.rb:79:in `routes'          from /home/ubuntu/workspace/config/routes.rb:4:in `block in <top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/routing/route_set.rb:434:in `instance_exec'          from /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/routing/route_set.rb:434:in `eval_block'          from /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/routing/route_set.rb:412:in `draw'          from /home/ubuntu/workspace/config/routes.rb:1:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:40:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:40:in `load_paths'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:16:in `reload!'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:26:in `block in updater'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/file_update_checker.rb:75:in `execute'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:27:in `updater'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `instance_exec'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `run'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:55:in `block in run_initializers'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:54:in `run_initializers'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application.rb:352:in `initialize!'          from /home/ubuntu/workspace/config/environment.rb:5:in `<top (required)>'          from /home/ubuntu/workspace/config.ru:3:in `block in <main>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'          from /home/ubuntu/workspace/config.ru:in `new'          from /home/ubuntu/workspace/config.ru:in `<main>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:61:in `app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:139:in `log_to_stdout'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:78:in `start'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:80:in `block in server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in `tap'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in `server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'          from /home/ubuntu/workspace/bin/rails:9:in `require'          from /home/ubuntu/workspace/bin/rails:9:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'          from /home/ubuntu/workspace/bin/spring:13:in `require'          from /home/ubuntu/workspace/bin/spring:13:in `<top (required)>'          from bin/rails:3:in `load'          from bin/rails:3:in `<main>'  

Rails 5 Create, Update and Delete won't work when trying to save

Posted: 25 Sep 2016 03:02 AM PDT

I am trying apply CRUD in rails but it didn't save any records for example, I have a model (database table) called Subject and it only has 2 fields (id, title). This is the code when I'm trying to create a record:

>> subject = Subject.create(:id => 'Comp1', :title => 'Word Processing')  (0.0ms)  BEGIN  #<Subject id: "Comp1", title: "Word Processing">  (0.0ms)  ROLLBACK  

the data only saved on an object, but not in the database, here is my code when i am trying to use the new/save

>> subject = Subject.new  #<Subject id: nil, title: nil>  >> subject.id = 'Comp1'  "Comp1"  >> subject.title = 'Word Processing'  "Word Processing"  >> >> subject.save  (0.0ms)BEGIN  (0.0ms)ROLLBACK  false  

I know that when i use the create method it will save automatically in the database, but in my case it wasn't.

when I used subject.errors, this is the result

>> subject.errors   #<ActiveModel::Errors:0x00000006b0d230 @base=#<Subject id: "Comp1", title: "Word Processing">, @messages={:course_group=>["must exist"]}, @details={:course_group=>[{:error=>:blank}]}>   

maybe it is because the subject_id is a foreign key inside course_group table. All I want is to add data to the subjects table without adding to the course_group table

Precompile assets without loading entire rails stack

Posted: 25 Sep 2016 01:40 AM PDT

In a rails application you can configure in application.rb which assets need to be precompiled. Then you have to run rake assets:precompile, which loads the entire rails stack.

Is it possible to precompile assets without loading anything from rails and/or my application? (apart from the gem dependencies that sprockets has).

Reason I ask is because I fail to see why I have to install all gems, including stuff like mysql, only to precompile assets? I wish it was more decoupled.

Start a dowload from external link in Rails

Posted: 25 Sep 2016 03:15 AM PDT

I'm trying to write code in my controller download to start a download from some external url say www.abc.com/foo.mp4. So far I have built it this way:

def download    redirect_to 'www.abc.com/foo.mp4'  end  

It works but the problem is that it opens a video in the same tab. What I want is that it should start a download in the browser of this video.

I searched about it in forums but couldn't find any solution. All I found was a way to download the video first using the URL and then provide it as download but that's not what I want. I want the download to start directly from the external URL.

No comments:

Post a Comment