Saturday, June 4, 2016

how to call method after range_field slider were used | Fixed issues

how to call method after range_field slider were used | Fixed issues


how to call method after range_field slider were used

Posted: 04 Jun 2016 06:36 AM PDT

i am fairly new to ruby. I build a user interface which scales over a value called zoom_factor. Next i implemented a button to test if i can change this value and pass it as a parameter. This works: (method: :get because of turbolink trouble)

<%= link_to "Refresh", ubersicht_path(:zoom_factor => 10), method: :get %>  

Next I tried to implement a slider which as I release the mouse button should fire the same method. But this does not work, the method is not called.

<%= range_field(:choosen_factor, ubersicht_path(:zoom_factor => :choosen_factor), method: :get, :in => 1..8, :step => 1) %>  

Any suggestions or totally new ways to solve this are welcome : )

Bootstrap styling not being applied to Rails page

Posted: 04 Jun 2016 06:43 AM PDT

I'm new to Rails, so have been following an online video tutorial building a project. I've been trying to add Bootstrap, but even after adding the Gem, doing a bundle install, restarting the mysql server, and adding the scss @bootsrap import to the application.css.scss file, it's still not pulling though to my index page.

Is there something I'm missing?

Group by Sum and Count of Table Records Rails

Posted: 04 Jun 2016 06:55 AM PDT

So i have a table with a listings which has various dates and amount.

e.g.   Date               Amount   2/1/2015           200  3/2/2015           300  7/2/2015           350  8/1/2015           400   

I want to be able to write a query which returns the sum of the amount grouped by month.

So e.g. Jan 600, Feb 650   

How do i do that in rails? Sql

Devise registration controller: I want to redirect path after save the data to different model

Posted: 04 Jun 2016 06:17 AM PDT

I saved additional data in devise registration but now i want to redirect when user model data and additional data were saved to different model. Application controller bur raise raise current_user.sellco.inspect only show nill class.

def after_sign_in_path_for(resource)  # root_path  raise current_user.inspect  if current_user.sellco    raise current_user.sellco.inspect    sellcos_path(resource.sellco)    # sellco_path  elsif current_user.buyco    buycos_path(resource.buyco)    # buyco_path  else    root_path  end  # case resource.fan  #   when resource.fan then  # end  

end

in registration controller

 def create  super      data = Additional.new(my_params)  data.save   end  

after that i want to redirect. also i found that without saving Additional mdoel data, it goes to application controller. i don't know why?

Wrong number of arguments 1 for 0 for form submission

Posted: 04 Jun 2016 06:49 AM PDT

This question has been there, in other posts. I have read them. But the problems in other questions, I cannot find in my code

Here is my view

 <%= simple_form_for :mail, url: forgot_pass_path, method: :post do |f| %>        <div class="a3" style="padding-top:20px;">        <center>          <div class="only-in-mobile">                <%= image_tag("Shijokes_Logo.png", alt: "Pets_Caricature", class: "img-responsive logo") %>                <!-- <img class="img-responsive logo" src="img/images/Shijokes_Logo.png" style=""> -->              </div>              <div style="padding-left:10%; padding-right:10%; padding-top:20%;">              <h2 style="font-size: 18px;              font-weight: 500;">Reset Password</h2>              <P class="" style="font-size: 13px;                      font-weight: 400; color:#666; margin-bottom:20px;">Enter the email address associated with your <br/>account we'll email you a link to reset<br/> your password</P>              <div class="form-group">                   <%= f.input :mail, required: true, label: false,  input_html: {class: 'form-control', placeholder: 'Enter email'} %>                </div>              <input type="submit" name="commit" value="SEND RESET" class="blue-button">              </div>        </center>        </div>        <!-- forgot password -->        <% end %>  

Here is the route

post 'forgot_pass' => 'forgot_password#send'  

Here is the controller

class ForgotPasswordController < ApplicationController      def send      byebug      mail = params[:mail]    end      end  

The error I am getting is

ArgumentError in ForgotPasswordController#send  wrong number of arguments (1 for 0)  

How to set the id of a post to it's title

Posted: 04 Jun 2016 05:56 AM PDT

I'm guessing this is fairly obvious, but I've been searching for a while and couldn't find anything. So what I want to do is have the id of a link be the same as @link.product How do I do that. Right now in my links controller I have

def create      @link = Link.new(link_params)      @link.id = @link.product  end  

But I still have /links/5 How do I change the ID so it shows up as /links/product-name ?

can not export a csv file through a rail application

Posted: 04 Jun 2016 06:27 AM PDT

I am trying to export a csv file through a rail application. I have a previous application which imports the data from a csv file and shows it in the webpage. That application was fired from the url http://localhost:3000/ and it was working fine.

But now I am trying to get back the data shown in the webpage back to a csv file which I can download from the page.

Now I am not sure why I am facing the error. The error is: Routing Error: uninitialized constant UsersController

My code is as follows:-

I created my app name is names My name\app\controllers\names_controller.rb file is:

class NamesController < ApplicationController  require 'csv'  def index   @names= Name.order(:name)   respond_to do |format|      format.html { redirect_to root_url }      format.csv {send_data @names.to_csv}      format.xls    end  end  end  

My name\app\models\names.rb file is:

class Name < ActiveRecord::Base  attr_accessible :age, :name    def self.to_csv(options = {})       CSV.generate(headers: true) do |csv|          csv << column_names          all.each do |name|              csv << name.attributes.values_at(*column_names)          end      end  end  end  

My name\app\views\names\index.html.erb file is:

<h1>Names</h1>    <p>  Download:  <%= link_to "CSV", names_path(format: "csv") %> |  <%= link_to "Excel", names_path(format: "xls") %>  </p>  

My name\app\views\names\index.xls.erb file is:

<table border="1">  <tr>  <th>Age</th>  <th>Name</th>  </tr>  <% @names.each do |name| %>  <tr>    <td><%= product.age %></td>  <td><%= product.name %></td>      </tr>  <% end %>    </table>  

My names\config\routes.rb file is:

Rails.application.routes.draw do    get 'users/index'    get 'users/import'    resources :users do  collection {post :import}  end  root to: "users#index"    end  

My previous application database screenshot is:- The columns names are Age and Name respectively

Ruby regex to match double mustache but not triple mustache

Posted: 04 Jun 2016 06:48 AM PDT

I am using mustache gem in my ruby on rails app. Given a template, I would like to replace all double mustache in the template with triple mustache, and not replace when it is a triple mustache. There won't be single mustache in the original template, so i don't want to worry about single mustache.

Eg:

temp = "You have just won {{value}} {{{currency}}}!"  

should convert to

temp = "You have just won {{{value}}} {{{currency}}}!"  

Rails 4 TypeError: no implicit conversion of Symbol into String

Posted: 04 Jun 2016 05:57 AM PDT

I'm trying to make a system for blocking users.

I'm trying to select battles that the user didn't block their owner

What i tried so far is :

blocked_user_list = BlockedUser.where(:blocker_user_id => user.id).pluck(:user_id)       # If the user blocked any users    if (blocked_user_list.length > 0)      battles = Battle.all.join(:users).where("battles.user_id NOT IN (?)", blocked_user_list)    end  

The structe of the tables

create_table "blocked_users", force: :cascade do |t|    t.integer  "user_id" # The id of the blocked user    t.integer  "blocker_user_id" # The id of the blocker user    t.datetime "created_at",      null: false    t.datetime "updated_at",      null: false  end    create_table "battles", force: :cascade do |t|    t.integer  "user_id"    t.string   "title"    t.datetime "created_at",                      null: false    t.datetime "updated_at",                      null: false  end  

The error im getting is : Rails 4 TypeError: no implicit conversion of Symbol into String

bootstrap SLIM ruby on rails modal with input needs to resize width instead of 100%

Posted: 04 Jun 2016 05:05 AM PDT

I'ved got this slim with ruby on rails. currently the input takes up the whole width of the screen. As this is a modal popup, it shouldnt be so big, maybe 50% of the screen size.

How can I control the modal or input width ? Thanks.

here is the input that caused it, removing this will not take up 100% of the width

= f.input :approved_management_note, class:"form-control"  

full modal code

#mgmtapproveModal.modal.fade[role="dialog"]    .modal-dialog    = simple_form_for @visitor, :url => approve_visitor_management_visitors_path, :method => :post do |f|      .modal-content        .modal-header          button.close[type="button" data-dismiss="modal"]            | ×          h4.modal-title            | Management Approve        .modal-body          p                        = f.input :approved_management_note, class:"form-control"        .modal-footer          button.btn.btn-default[type="button" data-dismiss="modal"]            | Close          = f.button :submit, "Management Approve", class:"btn btn-success"  

No such file or directory - the ffprobe binary could not be found error

Posted: 04 Jun 2016 04:40 AM PDT

I am using carrierwave-video gem uploading videos through carrierwave and it's not working.

video_uploader.rb

class VideoUploader < CarrierWave::Uploader::Base    include CarrierWave::Video    storage :file    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end  end  

video.rb

class Video < ActiveRecord::Base    mount_uploader :file, VideoUploader      def set_success(format, opts)      self.success = true    end  end  

The error I am getting is:

No such file or directory - the ffprobe binary could not be found in /home/administrator/.rvm/gems/ruby-2.3.0/bin:/home/administrator/.rvm/gems/ruby-2.3.0@global/bin:/usr/share/rvm/rubies/ruby-2.3.0/bin:/usr/share/rvm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games  

ffmpeg watermark has no affect on video

Posted: 04 Jun 2016 04:00 AM PDT

I'm using carrierwave to upload movies, and I want to use stremio-ffmpeg to wartermark the uploading video.

for this I have the following function in the uploader

gem 'streamio-ffmpeg', '1.0.0'  

The function is now in the carrierwave uploader and looks like this:

  process :watermark_movie      def watermark_movie        options = {watermark: "#{Rails.root}/public/images/logo_klein.png", resolution: "640x360", watermark_filter: {position: "RT", padding_x: 10, padding_y: 10},custom: '-strict experimental'}        #debugger        tmp_path = File.join File.dirname(current_path), "tmp_file.mp4"        file = FFMPEG::Movie.new(self.file.path)        file.transcode tmp_path, options        File.rename tmp_path, current_path    end  

At the moment there are no more errors, problem is that the watermark is not working.

What is my failure in this?

I connected my web with port 80 and it is connected, but the web shows 'Unable to connect'

Posted: 04 Jun 2016 04:01 AM PDT

I'm using Ruby on Rails and AWS server. I opened 80 port in my instance's security group, logged in my server through terminal, and typed

  $rvmsudo rails s -p 80  

And this is the result of the command.

enter image description here

So I opened my webpage with Safari, but the browser showed 'Unable to Connect'. I killed other background Rails processes and there was only one that is connected to the port. I can't get the reason the webpage is unable to connect.

How to show questions page by page in ruby on rails with previous and next link

Posted: 04 Jun 2016 04:20 AM PDT

How to show questions page by page in ruby on rails with next and previous link?

html2canvas function reloading all images on webpage

Posted: 04 Jun 2016 04:17 AM PDT

When I run html2canvas function it works fine, but it starts loading all images on the current webpage which takes too much time. Is it normal? or am I doing something wrong? Here is the code. There are just 2 images in tag1Div element which I am converting to image. But for some reason in the server log almost all images displayed on the current webpage are being loaded again.

    function genTag1(){          document.getElementById('loaderMsg').innerHTML='<img src="/assets/spinner.gif"> Generating Tag 1 Image...';          html2canvas($('#tag1Div'), {                      onrendered: function(canvas) {                      }                  });        }  

Ok I just realized by logging html2canvas process in log that for generating image html2canvas clones the entire document. This is why all assets and images are reloaded again. Is there any way to avoid this?

rails slim modal popup form

Posted: 04 Jun 2016 02:54 AM PDT

I'ved got this rails SLIM code which I am trying to create a modal popup to input a simple text form before submitting.

Im not sure how to do a modal popup for this.

here is my code:

https://gist.github.com/anonymous/2a6451b6714981667d2d4e349e3d7d32

Basically I want to trigger the modal popup for any of this two buttons and submit using this approve/reject route. Thanks.

      = link_to 'Management Approve', approve_visitor_management_visitors_path, class:"btn btn-success btn-block", data: {:confirm => 'Are you sure?'}        = link_to 'Management Reject', reject_visitor_management_visitors_path, class:"btn btn-danger btn-block", data: {:confirm => 'Are you sure?'}  

Can someone guide how to do this ? Thanks.

Need suggestion: what should I use to create an app like Buffer Pablo (demo inside)? [on hold]

Posted: 04 Jun 2016 02:47 AM PDT

I know Ruby on Rails and JavaScript (including jQuery) and I want to create a web app like Buffer Pablo (watch this 30 seconds video).

But I'm not really sure what tools, gem or JS library to use and I need suggestion for that.

The main feature that I'm going to build is going to have:

  • user can select a background image (already inside the app)
  • user can upload a photo of their own from their computer
  • user can place the uploaded photo freely within the canvas and scale it
  • user can add some texts, change the font and color of the text, scale and move the texts freely within the canvas
  • and finally, user can save their artwork as JPG file

Please help and suggest the tools, gems or JS library that can help me.

no implicit conversion of Symbol into Integer in ruby [on hold]

Posted: 04 Jun 2016 02:43 AM PDT

class UserController < ApplicationController      skip_before_action :verify_authenticity_token      require 'rubygems'      require 'mongo'        include Mongo        def create      begin          host = ENV['MONGO_RUBY_DRIVER_HOST'] || '127.0.0.1'          port = ENV['MONGO_RUBY_DRIVER_PORT'] || '27017'          puts "Connecting to #{host}:#{port}"          db = Mongo::Client.new(host, port).db(params[:dbname])          # Sample.with(database: "testdb").create()          # session_hash = {"database" => "testmongo", "hosts" => ["127.0.0.1:27017"], "username" => "", "password" => ""}          # Mongoid::Config.sessions[:mongo_dynamic] = session_hash      rescue Exception => e          render :json =>           {          :status => e.message,          }.to_json      end      end    end  

no implicit conversion of Symbol into Integer in ruby - Give the solutions and i need to create a database manually through the ruby .

How can I recompile my application.css.scss.erb asset after adding a new item to a collection in Ruby on Rails?

Posted: 04 Jun 2016 03:31 AM PDT

I am developing a rails application which allows admin users to add colors to a collection dynamically, and then apply those colors to a post via a reference to the color and a css class.

In my application.css.scss.erb file I have the following code:

<% Color.all.each do |color| %>      .theme-<%= color.name %>{          color: <%= color.text_color %>;          background: <%= color.hex_code %>;          border-top-color: <%= color.hex_code %>;      }  <% end %>  

As you can see, I am going through all colors in the Colors collection and creating a specific css class for each one to be applied in the view of my posts.

Each post has a reference to a color in the Colors collection, and therefore in my Post view I apply the class like so:

<div id="post-header" class="theme-<%= @post.color.name %>">      <h1><%= @post.title %></h1>      <%= link_to image_tag('post_header_image.png'), post_path(@post) %>  </div>  

I would like it so that an admin user can dynamically add a new color to the Colors collection via a form, and then have the application.css.scss.erb file compile automatically so that any new color classes can be applied right away, without having to manually refresh or update the application.css.scss.erb file.

The problem is that when I dynamically add a new Color to the color collection, my application.css.scss.erb file does not recompile and therefore the new color class is not created, so the actual color styles do not show up in my post view.

Is there any way to force rails to recompile my application.css.scss.erb file after adding a new color to the Colors collection?

Otherwise, is there a better way to handle dynamic styles and classes in Rails?

Rails Debugger won't let me start the rails server

Posted: 04 Jun 2016 02:19 AM PDT

I have installed Ruby 2.3.0 and Rails 4.2.6 and Byebug,as I found out that Debugger Inspector won't work with versions over 2.0.Everything worked just fine for a while,but then I had to restart my laptop because of an Ubuntu crash.Now,whenever I try to start my server again,this error will appear ~/blog$ bin/rails server Could not find rails-dom-testing-1.0.7 in any of the sources Run bundle install to install missing gems. But..when I try to install bundle AGAIN Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /tmp/bundler20160604-4983-kk24eqsqlite3-1.3.11/gems/sqlite3-1.3.11/ext/sqlite3  

/usr/bin/ruby2.3 -r ./siteconf20160604-4983-4lrmvd.rb extconf.rb mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20160604-4983-kk24eqsqlite3-1.3.11/gems/sqlite3-1.3.11 for inspection. Results logged to /tmp/bundler20160604-4983-kk24eqsqlite3-1.3.11/extensions/x86_64-linux/2.3.0/sqlite3-1.3.11/gem_make.out Using rdoc 4.2.2 Using tzinfo 1.2.2 Using loofah 2.0.3 Using rack-test 0.6.3 Using mime-types 3.1 An error occurred while installing debug_inspector (0.0.2), and Bundler cannot continue. Make sure that gem install debug_inspector -v '0.0.2' succeeds before bundling.

What should I do? Thanks.

What is the exact difference between development and production enviroments in Rack?

Posted: 04 Jun 2016 02:17 AM PDT

I am newbie on Ruby on Rails. Can't find much information about it.

Active admin user model attribute not submitting

Posted: 04 Jun 2016 02:15 AM PDT

I added an attribute to admin_users model of active admin, the attribut was added using a migration, the code for the migration is :

class AddHostelToAdminUsers < ActiveRecord::Migration    def change      add_column :admin_users, :hostel, :string    end  end  

now when I am submitting the form to generate new admin I am getting nothing on place of that attribute ,the object is being created with out :hostel attribute Details of user see the hostel filled is empty. I entered all details carefully : Form for creating admin

heroku cli: installing CLI issue in CMD even after the heroku toolebit is installed

Posted: 04 Jun 2016 01:18 AM PDT

Command Prompt shows the following error when heroku login command runs. The Heroku toolebit has been installed successfully still it is showing the error. Please help.

Microsoft Windows [Version 6.3.9600]  (c) 2013 Microsoft Corporation. All rights reserved.    C:\Users\Hemant>cd..    C:\Users>cd..    C:\>cd web    C:\web>cd .git    C:\web\.git>heroku login  heroku-cli: Installing CLI... !    Heroku client internal error.   !    Search for help at: https://help.heroku.com   !    Or report a bug at: https://github.com/heroku/heroku/issues/new    Error:       An existing connection was forcibly closed by the remote host.  - SSL_connect (Errno::ECONNRESET) (Excon::Errors::SocketError)  Command:     heroku login  Version:     heroku/toolbelt/3.43.2 (i386-mingw32) ruby/2.1.7  Error ID:    20d43dbd18674f768f85f7d97302dd63      More information in C:/Users/Hemant/.heroku/error.log  

C:\web.git>

How can I download the particular file which is uploaded using carrierwave?

Posted: 04 Jun 2016 05:52 AM PDT

Hi I am using Ruby 2 and Rails 4. I am uploading a pdf file and its stored in public/uploads/contact/file/15/abc.pdf because I am using CarrierWave, and in my file_uploader.rb the below code is written.

def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"   end  

Now I want to download the same file which I uploaded. How can I download that file? Please share with me if anyone has any idea. I am adding my code below.

Showing picture what I want to do exactly. Choosing a file upload it and then download it. enter image description here

My codes are:

downloads_form.html.erb

<table class="table table-condensed table-responsive">          <tbody>              <%= form_tag create_form_path,  multipart: true  do |f| %>              <tr>                                  <td>ABC</td>                  <td><%= file_field_tag "contact[file]",  class: "form-control" %></td>                  <td><%= submit_tag 'Upload' %></td>                  <td><%= link_to "Download", static_pages_downloadform_pdf_path %></td>                </tr>              <tr>                                 <td>DEF</td>                  <td><%= file_field_tag "contact[file]",  class: "form-control" %></td>                  <td><%= submit_tag 'Upload' %></td>                  <td><%= link_to "Download", static_pages_downloadform_pdf_path %></td>              </tr>              <% end %>             </tbody>      </table>  

static_pages_controller.rb

  def create_form      @form_downup = Contact.new(contact_params)      if @form_downup.save        redirect_to :back      else        render downloads_form_path      end    end      def downloadform_pdf      end     private      def contact_params         params.require(:contact).permit(:file)        end  

routes.rb

  match '/downloads_form', to: 'static_pages#downloads_form', via: 'get', as: :downloads_form    match '/create_form', to: 'static_pages#create_form', via: 'post', as: :create_form         get "static_pages/downloadform_pdf"  

Sort alphabetically and group by first letter

Posted: 04 Jun 2016 12:37 AM PDT

I'm currently doing a dictionnay, glossary here http://beta.emangaka.com/definitions

I sort the definition alphabetically.

definitions_controller.rb :

  def index      @definitions = Definition.all.order('title ASC')      @titre = "Définitions"    end  

index.html.erb

<% @definitions.each do |definition| %>  ...  

The list is too long and I'm looking for group by letter too always based on the first letter of "title".

How to do ? Merci. Thank you.

Creating dynamic instance methods in after_save callback rails

Posted: 04 Jun 2016 12:33 AM PDT

I have a after_save callback in a model named Field and i am creating dynamic instance methods in it on other model named User, but the code is not working, i am unable to figure out whats wrong with it, as the logic is very simple.Please help.

class field < ActiveRecord::Base      after_create :create_user_methods      private        def create_user_methods        User.class_eval do          define_method(self.name) do            #some code          end            define_method(self.name + "=") do            #some code          end        end      end    end  

and then I am creating Field instance in rails console like this

  Field.create(name: "test_method")  

And then calling that method on User class instance like this

  User.new.test_method  

But it raises error

undefined method test_method for ....

Relations Between 3 models in rails (Teacher,Subject,Student)

Posted: 04 Jun 2016 12:25 AM PDT

I need help to structure the relations between 3 models in rails Teacher, Subject and Student

I don't know if it is possible, but I hope so

a students can be in multiple subjects, and he belong to a teacher

a subject can have multiple students and it belongs to a teacher

Teachers may be able to add subjects and to acces all students

Struggling while trying to import a csv file in a rail application

Posted: 03 Jun 2016 10:58 PM PDT

I am going to create an rail application to import a csv file and showing its content in webpage. Everything is working fine except one thing. If the csv file contains quoted strings such as "", ",'' then the program is not working.

My app/models/user.rb file is :-

class User < ActiveRecord::Base    require 'csv'      def self.import(file)      CSV.foreach(file.path, headers:true) do |row|          User.create! row.to_hash      end   end  end  

NoMethodError - undefined method - ruby on rails - collection select dropdown

Posted: 03 Jun 2016 10:17 PM PDT

Im trying to do a drop down select box on ruby on rails but encounter the error below

error

NoMethodError - undefined method `typename' for {"typename"=>"dasds"}:Hash:  

view

  = f.input :visitortype, collection: @visitor_types_collection, label_method: 'typename', include_blank: false, required: true, class:"form-control"  

controller (whats wrong with this>)

  @visitor_types_collection = [{"typename" => "dasds"}]  

For Your Info, I am actually trying to put this in (the sample above is just to get some idea how its done):

{"visitor_types" => [{"typename" => "Friend",                           "require_mgmt_approval" => "false"},                          {"typename" => "Delivery",                           "require_mgmt_approval" => "true"},                          {"typename" => "Contractor",                           "require_mgmt_approval" => "true"}                          ]}  

Order #, SKU, random id string

Posted: 03 Jun 2016 09:30 PM PDT

When saving records for users, like orders, shipments, items, is it good to generate something different than the primary key for tracking?

If so, why do we do this?

If so, what is the best way to do this (in rails)?

If not, why do vendors/people provide random strings as order numbers, etc?

No comments:

Post a Comment