Thursday, December 29, 2016

Rails: examples of implementing jsTree | Fixed issues

Rails: examples of implementing jsTree | Fixed issues


Rails: examples of implementing jsTree

Posted: 29 Dec 2016 07:34 AM PST

Can anyone share some examples of how to implement jsTree view using AJAX, please? So far I've found few posts which do not show all process from controller to view + I need lazy loading example as I might have big amount of records.

I'd like to do treeview for records grouped by DateTime column. I'm using Rails 5, Postgresql 9.5.

Thank you!

How to add class to table row depending on condition rails?

Posted: 29 Dec 2016 07:23 AM PST

I have a table with Entries. Each entry has a datetime, text, calory. I need to make all rows green, if total calories for that day is less than expecting value, otherwise make it red. In my index action I have @total (which is the value to compare with) and in the end I have two arrays with good (green) dates and bad dates.

def index  @entries = Entry.all  @total = 50  @total2 = Entry.all  @a = {}  Entry.all.each do |entry|    if @a.key?(entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10])      @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += (entry.calory)    else        @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] = 0      @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += entry.calory    end  end  @good = []  @bad = []  @a.each do |c|    if c[1] < @total      @good.append(c[0])    else      @bad.append(c[0])    end  end  

end

Then in my index.html.erb I loop through the rows and try to change it's color, if the value is in good or bad array. But it colors everything green.

  <script type="text/javascript">    var a = '<%=@a%>';    var final = '<%=@final%>';    var good = '<%=@good%>';    var bad = '<%=@bad%>';    console.log(good);    $('#entries tr').each(function() {      var date = $(this).find("td:first-child").text();      if (good.substring(date) !== -1) {        $(this).find("td:first-child").addClass('good');      } else {        $(this).find("td:first-child").addClass('bad');      }  });    </script>  

Here is my table

Time    Text    Calory  Show    Edit    Destroy   2016-12-24 10:00:00 first   23  Show    Edit    Destroy  2016-12-24 11:58:00 second  45  Show    Edit    Destroy  2016-12-24 12:59:00 third   56  Show    Edit    Destroy  2016-12-28 12:29:00 sds 34  Show    Edit    Destroy  2016-12-24 10:00:00 dewq    34  Show    Edit    Destroy  

Here is console.log(good): ["2016-12-28 "] Here is console.log(bad): ["2016-12-24 "]

Here is console.log(date) for each date:

2016-12-24 10:00:00  2016-12-24 11:58:00  2016-12-24 12:59:00  2016-12-28 12:29:00  2016-12-24 10:00:00  

ExecJS::RuntimeError: SyntaxError: Unexpected token: name (catch) (line: 41, col: 8, pos: 1392)

Posted: 29 Dec 2016 07:23 AM PST

I'm trying to add a service worker to my Rails app with the serviceworker gem.

I've been following this guide https://rossta.net/blog/offline-page-for-your-rails-application.html and started receiving the error listed in the title.

I've reviewed other questions similar, but most are due to syntax errors. As this post Rails 5 Heroku deploy error: ExecJS::ProgramError: SyntaxError: Unexpected token: name (autoRegisterNamespace)

My error is due to the token name (catch) which was supplied via the serviceworker gem file.

Here is my code where the error is occurring ...

 function onFetch(event) {     // Fetch from network, fallback to cached content, then offline.html for same-origin GET requests     var request = event.request;       if (!request.url.match(/^https?:\/\/example.com/) ) { return; }     if (request.method !== 'GET') { return; }       event.respondWith(       fetch(request).                                       // first, the network          .catch(function fallback() {            caches.match(request).then(function(response) {  // then, the cache              response || caches.match("/offline.html.erb");     // then, /offline cache            })          })      );  

I understand the error is at .catch , I'm just not sure how to solve the issue.

Any help is much appreciated, thanks!

Rails: how to automatically create models from an sql file

Posted: 29 Dec 2016 07:13 AM PST

I have an sql file with respective create table statements (and columns, keys etc.). Is there a way to automatically generate models (if not even scaffolds) from this? Thanks in advance

how to detect if you are running outside of the rails main app

Posted: 29 Dec 2016 06:44 AM PST

How can I detect that code is running outside the main rails app?

For example in a console, or in a rake task, or as part of a scheduler action, etc.

I understand that there are specific ways to do this for each case (i.e. check Rails::Console etc, but I am looking for a general way to this that will work for all cases.

To clarify a bit further. By "main rails app" I mean the "instance" of rails that is responding to http requests.

Model's attributes are being failed validation when they are not passed

Posted: 29 Dec 2016 06:48 AM PST

Is it logical that when I don't pass attributes' values, they failed the validation of the custom validation method, even though I am not trying to update them, however, the value is valid, and it was created successfully at the first place.

   Parameters: {"utf8"=>"✓", "id"=>"2", "shop"=>{"allowed_users"=>"5"}, "commit"=>"עדכן"}  

The validation fails only for the custom validation method, for :shop_customer_id.

Rails error: "param is missing or the value is empty" suddenly after remove gem

Posted: 29 Dec 2016 05:47 AM PST

When i create a task an ajax function is called to send a specific params data. It was working very well. Then i've installed "wicked_pdf" and "wkhtmltopdf-binary". After learning that on windows I have problems with this tools, i removed them by using "gem uninstall wicked_pdf/wkhtmltopdf-binary". (I removed manually all wicked_pdf config file). After this when i create a new task I have this error on my rails application (windows): " param is missing or the value is empty: task". If I delete the ajax code it works fine but not as before.

Ajax (was working very well):

$( "#new_task" ).submit(function(event) {  event.preventDefault();  var value = $('#task_value').val().replace(assignee,'');  value.replace(/&nbsp;/g,'');  $('#new_task').find('input[name="task[value]"]').val().replace(assignee,'');     $.ajax({     url: "/tasks",     type: "post",     contentType: "application/json",       data: JSON.stringify({ assignee: assignee, value: value }),     success: function(data) {         alert('successfully');     },     error: function(xhr, textStatus, error) {       alert(xhr.statusText+" "+textStatus+" "+error);     }  });    });    

controller (it was working, i never changed it):

def create      @task = Task.new(task_params)      @task.user = current_user      set_date      set_category      respond_to do |format|        if @task.save          format.html { redirect_to tasks_url, notice: 'Task was successfully created. '+task_params.inspect}            #format.html { redirect_to @task, notice: 'Task was successfully created.' }          format.json { render :show, status: :created, location: @task }        else          format.html { render :new }          format.json { render json: @task.errors, status: :unprocessable_entity }        end      end    end  

And then in the index view i have this partial <%= render 'form', task: @task %> to a standard form (value and submit, with create action). What's the problem? I messed up with wicked_pdf?

Define article owner ( Couldn't find Article without an ID)

Posted: 29 Dec 2016 07:34 AM PST

I'm trying to define an article owner, for that I have to independent resources, which are not nested in each other (user, article).

Each article has an user_id attribute which corresponds to the id of the user who created the article.

Now I'm trying to match both so I can create an article owner.

This is how I'm trying to do it:

Articles_controller.rb

def show        @article = Article.find(params[:id])        @user_id = Article.find(params[:user_id])        @user= User.find_by(id: user_id)  end  

Ruby get page content

Posted: 29 Dec 2016 05:40 AM PST

I have a Ruby app and I want to detect if a certain piece of Javascript is installed on a website. On most websites it's no problem to fetch the content of this page with the following code:

user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.854.0 Safari/535.2"  doc = Nokogiri::HTML(open(url, 'User-Agent'=>user_agent, 'read_timeout' => '10'), nil, "UTF-8")  

But on some websites I get a Net::OpenTimeout: execution expired error after 60 seconds. How is it possible that some fetch and some don't and how can I fetch those websites as well?

Capistrano deploy:assets:precompile task fails by uninitialized constant error

Posted: 29 Dec 2016 05:16 AM PST

I got following error when I run bundle exec cap production deploy to deploy my project.

00:24 deploy:assets:precompile        01 RBENV_ROOT=~/.rbenv RBENV_VERSION=2.3.3 ~/.rbenv/bin/rbenv exec bundle exec rake assets:precompile        01 rake aborted!        01 NameError: uninitialized constant XBRL::FiguresController        01 /var/www/example.com/releases/20161229130354/lib/edgar/xbrl.rb:3:in `<class:XBRL>'        01 /var/www/example.com/releases/20161229130354/lib/edgar/xbrl.rb:1:in `<top (required)>'  

But bundle exec cap production deploy:assets:precompile runs without error.

And I have following files:

lib/edgar/xbrl.rb

class XBRL    include FiguresController    #...  end  

lib/edgar/figures_controller.rb

module FiguresController    #...  end  

config/application.rb

module MyProject    class Application < Rails::Application      Dir[File.join(Rails.root, 'lib', 'edgar', '*.rb')].each { |l| require l }    end  end  

I can use this XBRL class in rails console. I have no idea why the deploy:assets:precompile throws a error and why there is no error when I run it separately.

How can I fix this error? Am I putting the files wrong places? I'm using rails 5.0.0.

When deploying to Heroku, is there something I need to add/change in the production entry in the database.yml?

Posted: 29 Dec 2016 05:07 AM PST

I am using postgresql as the database in my development environment, so that means that I setup my database.yml like the code below where the username and password is my postgresql's username and password (obviously, I'm using environment variables to avoid hard-coding) and will be inherited by development and test environments:

default: &default    adapter: postgresql    encoding: unicode    # For details on connection pooling, see rails configuration guide    # http://guides.rubyonrails.org/configuring.html#database-pooling    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>    host: localhost    username: <%= ENV['PINTERESTING_APP_DATABASE_USERNAME'] %>    password: <%= ENV['PINTERESTING_APP_DATABASE_PASSWORD'] %>  

I'm just curious about the production environment, which has the code below:

production:    <<: *default    database: pinteresting_app_production    username: pinteresting_app    password: <%= ENV['PINTERESTING_APP_DATABASE_PASSWORD'] %>  

Unlike in the development and test environments which uses my postgresql's username and password, the production environment have different values for username and password.

My question is, do I need to change the username and password in the production environment? or should I just leave it as it is?

Genearte custom builder in rails

Posted: 29 Dec 2016 04:57 AM PST

I wanted to make a new custom builder in rails for a two text field to be used for range(seprated by -) field in rails

I tried something like

<%= form_for :range, :url=>{:controller=>"skills",:action=>"create"},:html=>{:multipart => true}, :builder => ComponentBuilder do |f| %>      <%= f.text_range_field :min_value,:max_value, :value => min_value, :id => 'value-min' %>        <%end%>  

my custom field builder is like

class ComponentBuilder < ActionView::Helpers::FormBuilder  def text_range_field(obj1,obj2,label,*args)  opts = args.last.is_a?(Hash) ? args.pop : {}  human = (opts[:label] unless opts.blank?) || label.to_s.humanize  args << (opts[:class].blank?? opts.merge!({ class: "tab_general_input" }): opts)  mandatory_text = (opts[:mandatory] == true)? ("<span class=\"mandatory\"> *</span>") : ""  content_tag("ul" ,    content_tag("li" ,      content_tag("label" ,        mandatory_text.html_safe + human.to_s.html_safe,        for: "#{@object_name}_#{label}" ), class: "tab_general_title") +      content_tag("li" ,text_field('','',*args)+text_field_tag('','',*args), class: "tab_general_info"))       end  

but it does not produces any result, any ideas where i might be doing wrong

Rails: Better syntax for respond_to (shorthand)

Posted: 29 Dec 2016 05:09 AM PST

I have the following code for the update method of a user settings controller:

def update    @user = ...    if @user.update_attributes(params[:user])      flash[:success] = 'Some success message.'      respond_to do |format|        format.html { redirect_to some_path }        format.js   { head :ok }      end    else      flash[:error] = 'Some error message.'      render action: 'some action'    end  end  

I'm wondering if there a way to shorten this whole method? Best option would be to reduce the number of lines for the respond_to block, if there's a way to use some shorthand syntax in there.

Rails devise gem with rails-settings

Posted: 29 Dec 2016 04:51 AM PST

I have a simple User model created with devise. I add additional attributes like username, birthday. Now I would like to add more user settings like Boolean public. But since I am aware that this attribute (i call them privacy settings) will not be the last created by me, I need a solution where I can expand the user settings easily without always updating the User modal. This is why I added rails-settings to my gem.

Now my question here first, is this best practise what I am doing here? And secondly, is there a good way to combine rails-settings with devise or is it better if I just use them seperatly. I am talking about the registration/edit.html.erb view, because there you can show all user fields but for my example not the rails-settings one.

bind rails app on the IP provided by the host with 3000 port

Posted: 29 Dec 2016 05:05 AM PST

I am running the rails app on VPS server provided by my host.

I need to run the same local app to the IP provided by them.

For eg myip:3000

Is it possible to do this, the IP provided by the host is a public/global IP.

How can I do this? Sorry for the dumb question.

Action Controller: Exception | undefined method `fetch_value' for nil:NilClass

Posted: 29 Dec 2016 04:53 AM PST

I am always getting this error message:

NoMethodError in ListsController#new undefined method `fetch_value' for nil:NilClass

Extracted source (around line #8):

7 def new
8 @list = List.new
9 end

I don't get the reason for this error ^^

My routes.rb

Rails.application.routes.draw do    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html      root 'lists#index'        get 'home' => 'lists#index', as: 'home'      get 'new' => 'lists#new', as: 'new'        resources :lists    end  

Database name:

:lists


Model name:

list

lists_controller:

class ListsController < ApplicationController        def index           @lists = List.all      end        def new         @list = List.new      end        def show           @list = List.find(params[:id])      end        def create          @list = List.new(list_params)            if(@list.save)              redirect_to @list          else              render 'new'          end      end        def edit          @list = List.find(params[:id])      end        def update         @list = List.find(params[:id])            if(@list.update(list_params))              redirect_to @list          else              render 'edit'          end      end        def destroy         @list = List.find(params[:id])             @list.destroy            redirect_to lists_path      end        private def list_params         params.require(:list).permit(:date, :class, :lesson, :subject, :teacher, :room, :info)       end  end  

new.html.erb

<%= form_for :list, url: lists_path do |f| %>      <% if @list.errors.any? %>          <% @list.errors.full_messages.each do |error| %>              <div class="alert alert-danger"><%= error %></div>          <% end %>      <% end %>      <div class="alert alert-info">Please fill out all the fields below.</div>      <p>          <%= f.label :date %><br>          <%= f.text_field :date, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :class %><br>          <%= f.text_area :class, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :lesson %><br>          <%= f.number_field :lesson, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :subject %><br>          <%= f.text_field :subject, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :teacher %><br>          <%= f.text_field :teacher, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :room %><br>          <%= f.text_field :room, {:class => 'form-control'} %>      </p>      <p>          <%= f.label :info %><br>          <%= f.text_area :info, {:class => 'form-control'} %>      </p>      <p>          <%= f.submit({:class => 'btn btn-info'}) %>      </p>  <% end %>  

Using the BootstrapCDN and only the default gems.

Thanks for any answers :)

create posts with devise user id using rake and faker gem

Posted: 29 Dec 2016 04:01 AM PST

I am a noobie. I am trying to generate fake data with faker gem using rake populate task I am getting error Validation failed User must exist. Here is my task file:

 namespace :db do    desc "Fill database with test data"    task populate: :environment do     10.times do |u|       name = Faker::LordOfTheRings.character       email = Faker::Internet.email       password = "password"       User.create!( name: name,                  email: email,                  password: password,                  password_confirmation: password)        end       User.all.each do |user|       10.times do |n|         title = Faker::Lorem.sentence         body = Faker::Lorem.paragraphs(1)         created_at = 2.years.ago..Time.now         user_id = user.id         Post.create!(                    title: title,                    body: body,                    created_at: created_at,                    user_id: user_id                                  )            end       end     end   end  

And i need to have the user references in my post table as well. Thanks in advance

creating a new column datatype in rails

Posted: 29 Dec 2016 04:03 AM PST

I might have not been searching for the right words in order to get an answer, so you were my last chance.

I am looking to create a new datatype in rails, for example: t.israeli_id

which gets to pass a customized validation method, and adds errors according to it.

I will be using this datatype in several tables, so making it a string, and passing the validation function in each model.rb would be so much not DRY.

I am using Postgresql, just in case that would matter.

Followers model in Rails

Posted: 29 Dec 2016 06:22 AM PST

In my app Users can follow each other. I have two tables: users and followers.

users    id  name    followers    id  user_id  follower_id  

And two models:

class User < ActiveRecord::Base      has_many :followers    belongs_to :follower    end    class Follower < ActiveRecord::Base      belongs_to :user    end  

What I want to do is list the followers for a user. e.g.

<ul>    <% @users.each do |user| %>        <li><%= user.name %></li>        <ul>          <% user.followers.each do |follower| %>              <li><%= follower.name %></li>          <% end %>        </ul>    <% end %>  </ul>  

However it doesn't look to be seeing the association...


After updating my model as per Deep's suggestions I got it working... however I'm unable to query followers and following users.

e.g.

I have two methods in my UsersController:

def user_followers    @user = User.where(id: params[:id]).first    @followers = @user.get_followers  end    def user_following    @user = User.where(id: params[:id]).first    @following = @user.get_following  end  

and then in my User model I have:

def get_followers    Follower.where(follower_id: self.id)  end    def get_following    Follower.where(user_id: self.id)  end  

Which should be returning the followers for the user or who the user is following. The views look like so:

<% @followers.each do |follower| %>      <%= follower.user.name %>  <% end %>    <% @following.each do |following| %>      <%= following.user.name %>  <% end %>  

However it only returns the name of the user I'm supposed to be viewing.

The Follower model now looks like:

class Follower < ActiveRecord::Base      belongs_to :user, foreign_key: 'follower_id', class_name: 'User'    end  

heroku postgresql database rails app PG::UndefinedTable: ERROR: relation "comments" does not exist

Posted: 29 Dec 2016 03:53 AM PST

i was run:

git push heroku master  heroku bin/rails db:migrate  

ignore success create tables (date too much), just show error part.

== 20161127134205 AddArticleIdToComment: migrating ============================  -- add_column(:comments, :article_id, :integer)  D, [2016-12-29T11:14:54.118466 #4] DEBUG -- :    (2.1ms)  ALTER TABLE "comments" ADD "article_id" integer  D, [2016-12-29T11:14:54.123821 #4] DEBUG -- :    (5.0ms)  ROLLBACK  D, [2016-12-29T11:14:54.127986 #4] DEBUG -- :    (3.7ms)  SELECT pg_advisory_unlock(4403768336151726570)  rails aborted!  StandardError: An error has occurred, this and all later migrations canceled:  PG::UndefinedTable: ERROR:  relation "comments" does not exist  : ALTER TABLE "comments" ADD "article_id" integer  

run heroku run rails c -> ActiveRecord::Base.connection.tables show:

=> ["schema_migrations", "ar_internal_metadata", "users", "articles"]  

but run Comment.connection unbelievable could connection and run Comment show

=> Comment(Table doesn't exist)  

Gemfile:

source 'https://rubygems.org'  gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.2'  gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'  group :development, :test do    gem 'byebug', platform: :mri  end  group :development do    gem 'web-console'    gem 'listen', '~> 3.0.5'    gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'  end  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  gem 'bootstrap-sass', '~> 3.3', '>= 3.3.7'  gem 'haml', '~> 4.0', '>= 4.0.7'  gem 'devise', '~> 4.2'  gem 'simple_form', '~> 3.3', '>= 3.3.1'  gem 'paperclip', '~> 5.1'  gem 'searchkick', '~> 1.4'  gem 'will_paginate', '~> 3.1', '>= 3.1.5'  gem 'will_paginate-bootstrap', '~> 1.0', '>= 1.0.1'  group :development, :test do    gem 'sqlite3'  end  group :production do    gem 'pg'  end  

schema.rb:

ActiveRecord::Schema.define(version: 20161225092307) do      create_table "articles", force: :cascade do |t|      t.string   "title"      t.text     "text"      t.datetime "created_at",               null: false      t.datetime "updated_at",               null: false      t.integer  "user_id"      t.integer  "node_id"      t.string   "article_img_file_name"      t.string   "article_img_content_type"      t.integer  "article_img_file_size"      t.datetime "article_img_updated_at"    end      create_table "comments", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "article_id"      t.integer  "raty"      t.text     "body"      t.integer  "user_id"    end      create_table "nodes", force: :cascade do |t|      t.string   "nodeName"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "notes", force: :cascade do |t|      t.text     "text"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"    end      create_table "suggestions_texts", force: :cascade do |t|      t.string   "text"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end    end  

table association:

Article:

  class Article < ApplicationRecord      searchkick    has_many :comments, dependent: :destroy    belongs_to :user    belongs_to :node    has_attached_file :article_img, styles: { index_img: "300x300>", show_img: "100x100>" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :article_img, content_type: /\Aimage\/.*\z/  end  

Comments:

   class Comment < ApplicationRecord          belongs_to :article        belongs_to :user     end  

problem is: PG::UndefinedTable: ERROR: relation "comments" does not exist

have some way would solve ?

thanks

How to query based on an association not having a specific value?

Posted: 29 Dec 2016 05:04 AM PST

Lets say I have 2 models:

class User  has_many :books  end    class Book  belongs to :user  end  

and let's say that book has only one field: Title.

How do I query for the users that dont have a book with title "abc"???

I tried the following:

User.left_outer_joins(:books).group("users.id, books.title").having("COUNT(books.title) = 0 or books.title != #{title}")  

The problem with this query is that if the user has 2 books ("abc" and "xyz") it will still return it.

Any ideas?

Rails / jQuery: How to check for parameters

Posted: 29 Dec 2016 02:49 AM PST

I've got the following script that gets executed via AJAX in Rails and uses the ERB Template:

Problem
It appears that only the first specified option (unchecking) works for switches and checkboxes works, the part inside the else statements does not work!

<% if params[:type] == "switch" %>      var obj = $('.<%= params[:name] %> a:not(.label) #myonoffswitch:checkbox');      <% if params[params[:name]] %>          $('.<%= params[:name] %> a:not(.label)').attr("href", "/update?name=abc&abc=true&type=switch");          obj.prop('checked', false);      <% else %>          $('.<%= params[:name] %> a:not(.label)').attr("href", "/update?name=abc&abc=false&type=switch");          obj.prop('checked', true);      <% end %>  <% elsif params[:type] == "checkbox" %>      <% if params[params[:name]] %>          $('.<%= params[:name] %> a:not(.label)').remove();          $('.<%= params[:name] %>').prepend("<a data-remote='true' href='/update?name=<%= params[:name] %>&amp;<%= params[:name] %>=true&amp;type=checkbox'><i class='icon ion-android-checkbox-outline-blank' tabindex='0'></i></a>");          $('.<%= params[:name] %> a:not(.label) i').focus();      <% else %>          $('.<%= params[:name] %> a:not(.label)').remove();          $('.<%= params[:name] %>').prepend("<a data-remote='true' href='/update?name=<%= params[:name] %>&amp;<%= params[:name] %>=false&amp;type=checkbox'><i class='icon ion-android-checkbox' tabindex='0'></i></a>");          $('.<%= params[:name] %> a:not(.label) i').focus();      <% end %>  <% end %>  

DOM

      <div class="name flex">          <a data-remote="true" href="/update?name=name&amp;name=false&amp;type=switch"><div class="onoffswitch">            <input checked="" class="onoffswitch-checkbox" id="myonoffswitch" name="onoffswitch" type="checkbox">            <label class="onoffswitch-label" for="myonoffswitch"></label>          </div>          </a>          <div class="label">            <a class="abc label" data-remote="true" href="/update?name=name&amp;name=false&amp;type=switch">ABC            </a>            <p class="abc labeltext">Lorem ipsum.</p>          </div>        </div>          <div class="name1 flex"><a data-remote="true" href="/update?name=name1&amp;name1=true&amp;type=checkbox">          <i class="icon ion-android-checkbox-outline-blank" tabindex="0"></i></a>            <div class="label">            <a class="abc label" data-remote="true" href="/update?name=name1&amp;name1=false&amp;type=checkbox">ABC            </a>            <p class="abc labeltext">Lorem ipsum.</p>          </div>        </div>  

However, I noticed that only if a checkbox or a switch is checked it gets unchecked, and if it is unchecked it will not change it's appearance (the DOM).

What am I doing wrong?

Devise 4 updating custom added fields to user model

Posted: 29 Dec 2016 03:17 AM PST

Im using Devise 4, Rails 5 and have a user model with the following fields added to the standard User model provided by devise:

class AddFieldsToUsers < ActiveRecord::Migration[5.0]    def change      add_column :users, :name, :string      add_column :users, :username, :string      add_column :users, :headline, :string      add_column :users, :location, :string      add_column :users, :description, :text    end  end  

In the account_update page, i want to enable the user to edit these fields along with the password, so i set up the following in views/devise/registration/edit:

      <div class="row">          <div class="col-xs-12 col-sm-8">            <div class="card">              <div class="card-header">                <h6>Profile</h6>              </div>                <div class="card-block">                <div class="form-horizontal">                  <div class="form-group">                    <label for="input1" class="col-sm-2 control-label">Name</label>                    <div class="col-sm-10">                      <%= f.text_field :name, class:"form-control", id:"input1" %>                    </div>                  </div>                    <div class="form-group">                    <label for="input2" class="col-sm-2 control-label">Username</label>                    <div class="col-sm-10">                      <%= f.text_field :username, class:"form-control", id:"input2" %>                    </div>                  </div>                    <div class="form-group">                    <label for="input3" class="col-sm-2 control-label">Email</label>                    <div class="col-sm-10">                      <%= f.email_field :email, class:"form-control", id:"input3" %>                    </div>                  </div>                    <hr>                    <div class="form-group">                    <label for="input4" class="col-sm-2 control-label">Headline</label>                    <div class="col-sm-10">                      <%= f.text_field :headline, class:"form-control", id:"input4" %>                    </div>                  </div>                    <div class="form-group">                    <label for="input5" class="col-sm-2 control-label">Location</label>                    <div class="col-sm-10">                      <%= f.text_field :location, class:"form-control", id:"input5" %>                    </div>                  </div>                    <div class="form-group">                    <label for="input6" class="col-sm-2 control-label">Description</label>                    <div class="col-sm-10">                      <%= f.text_area :description, class:"form-control", id:"input6", rows:4 %>                    </div>                  </div>                    </div>              </div>            </div>              <div class="card">              <div class="card-header">                <h6>Passwords</h6>              </div>                <div class="card-block">                <div class="form-horizontal">                  <div class="form-group">                    <label for="input1" class="col-sm-2 control-label">New password</label>                    <div class="col-sm-10">                      <%= f.password_field :password, class:"form-control"%>                    </div>                  </div>                    <div class="form-group">                    <label for="input2" class="col-sm-2 control-label">Confirm password</label>                    <div class="col-sm-10">                      <%= f.password_field :password_confirmation, class:"form-control"%>                    </div>                  </div>                    <div class="form-group">                    <label for="input3" class="col-sm-2 control-label">Current password</label>                    <div class="col-sm-10">                      <%= f.password_field :current_password, class:"form-control"%>                    </div>                  </div>                  <div class="form-group">                    <div class="col-sm-offset-2 col-sm-10">                      <%= f.submit "Update", class:"btn btn-primary btn-sm" %>                    </div>                  </div>                  </div>              </div>            </div>            </div>            <div class="col-xs-12 col-sm-4">            <div class="card">              <div class="card-header">                <h6>Avatar</h6>              </div>                <div class="card-block">                    <br>                  <button class="btn btn-primary btn-sm">Update</button>              </div>            </div>          </div>        </div>          <% end %>  

I have followed the devise 4 strong param changes and in my application_controller.rb iv got the following:

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception      before_action :configure_permitted_parameters, if: :devise_controller?      protected      def configure_permitted_parameters      added_attrs = [:name, :username, :location, :headline, :description, :email, :password, :password_confirmation]      devise_parameter_sanitizer.permit :sign_up, keys: added_attrs      devise_parameter_sanitizer.permit :account_update, keys: added_attrs    end    end  

Even with the following, this does not seem to update the fields?

In my application_controller.rb i have also tried:

  def configure_permitted_parameters      devise_parameter_sanitizer.permit(:sign_up, keys: [:name])      devise_parameter_sanitizer.permit(:account_update, keys: [:name, :username, :location, :headline, :description])    end  

How to add attributes to rails params in a controller and pass to different controller

Posted: 29 Dec 2016 02:42 AM PST

upload_controller   def create    file = @upload.file    content = File.read file    params['content'] = content   end  end  

Here params['content'] has proper file content.

book_controller   def create    @book.description = params['content']    @book.save   end  end  

But params['content'] in book_controller returns nill

How can I pass content from upload controller to book controller?

Capistrano assets:precompile , undefined $modal-delay for css

Posted: 29 Dec 2016 02:25 AM PST

Following is my deploy.rb

# config valid only for current version of Capistrano  lock '3.7.0'    set :linked_dirs,  %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}    namespace :puma do    desc 'Create Directories for Puma Pids and Socket'    task :make_dirs do      on roles(:app) do        execute "mkdir #{shared_path}/tmp/sockets -p"        execute "mkdir #{shared_path}/tmp/pids -p"      end    end      before :start, :make_dirs  end        namespace :deploy do    desc "Make sure local git is in sync with remote."    task :check_revision do      on roles(:app) do        unless `git rev-parse HEAD` == `git rev-parse origin/master`          puts "WARNING: HEAD is not the same as origin/master"          puts "Run `git push` to sync changes."          exit        end      end    end      desc 'generate sitemaps'    task :generatesitemap do      on roles(:app) do        execute "cd #{release_path}"        execute "ruby sitemap.rb"      end    end      desc 'Initial Deploy'    task :initial do      on roles(:app) do        before 'puma:start'        invoke 'deploy'      end    end      desc 'Restart application'    task :restart do      on roles(:app), in: :sequence, wait: 5 do        # invoke 'puma:restart'        Rake::Task['puma:restart'].reenable      end    end      before :starting,     :check_revision    after  :finishing,    :compile_assets    after  :finishing,    :cleanup    after  :finishing,    :generatesitemap    after  :finishing,    :restart  end    # ps aux | grep puma    # Get puma pid  # kill -s SIGUSR2 pid   # Restart puma  # kill -s SIGTERM pid   # Stop puma  

Following is my capfile

# Load DSL and set up stages  require "capistrano/setup"    # Include default deployment tasks  require "capistrano/deploy"    require 'capistrano/rails'  require 'capistrano/bower'  require 'capistrano/bundler'  require 'capistrano/rvm'  require 'capistrano/puma'  require 'capistrano/puma/nginx'  # Load custom tasks from `lib/capistrano/tasks` if you have any defined  Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }  

When I deploy to staging environment. I am constantly getting this error "Sass::SyntaxError: Undefined variable: "$modal-delay"

I have searched through my stylesheets and I don't have this variable $modal-delay used anywhere in my stylesheets. I also tried defining this variable in application.scss. but still this error keeps coming.

I have also cleaned, clobbed my assets, i have also cleared my tmp/cache folder.

Following is my application.scss file

$modal-delay : 3;       @import "animate.scss";   @import "bootstrap.scss";   @import "font-awesome.scss";   @import "material-design-iconic-font.scss";   @import "reset.scss";   @import "responsive-menu.scss";   @import "owl.carousel.scss";   @import "easy-responsive-tabs.scss";   @import "mediaelementplayer.scss";   @import "style1.scss";   @import "responsive.scss";   @import "custom.scss";   @import "messenger/build/css/messenger.css";   @import "messenger/build/css/messenger-theme-future.css";   @import "bootstrap-suggest.scss";  

Assets.rb file

Be sure to restart your server when you modify this file.

# Version of your assets, change this if you want to expire all your assets.  Rails.application.config.assets.version = '1.0'    # Add additional assets to the asset load path  # Rails.application.config.assets.paths << Emoji.images_path    # Precompile additional assets.  # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.    Rails.application.config.assets.precompile += %w( application.js )  Rails.application.config.assets.precompile += %w( application.css )  

I am looking at this thread https://groups.google.com/forum/#!topic/twitter-bootstrap-stackoverflow/CleVNc6SOGw

Thanks

Rails 4: Show List of Items in third level associations

Posted: 29 Dec 2016 01:51 AM PST

I have Following structure in my rails app.

class Country < ActiveRecord::Base    has_many :states  end    class State < ActiveRecord::Base    has_many :cities    belongs_to :country  end    class City < ActiveRecord::Base    belongs_to :state  end  

I want to access to cities from the country model. e.g. @country.cities. Also, how can I get the country from city model? e.g @city.country

Thanks,

Undefined render_to_string method in background job while using wicked_pdf in rails [duplicate]

Posted: 29 Dec 2016 01:39 AM PST

This question already has an answer here:

I am trying to generate a pdf, upload it to server and gives the server url of the stored pdf as response

The controller api code is as follows

 module Api  module V0      class InvoiceApiController < ApiController            def order_invoice              response = Hash.new              result = Hash.new              if params[:txnid] && params[:total_amount]!= nil                   @order = Invoice.new(order_id: params[:id])                  @order.txnid = params[:txnid]                  @order.stamp_amount = params[:stamp_amount] || ''                  @order.service_name = params[:service_name] || ''                  @order.landmark = params[:landmark] || ''                  :                  :                  @order.no_of_copies = params[:no_of_copies]                  @order.save!               upload = InvoiceJob.perform_later(@order.txnid)                 response['result'] = upload                 response.merge! ApiStatusList::OK              else                  response.merge! ApiStatusList::INVALID_REQUEST              end               render :json => response             end          end          end          end  

The background job code using resque gem is:

class InvoiceJob < ActiveJob::Base  require 'wicked_pdf'  queue_as :invoice    def perform(*args)      txnid = args[0]      debugger      order = Invoice.where(txnid: txnid).first       pdf = WickedPdf.new.pdf_from_string(                  render_to_string(template:       'invoices/generate_invoice.pdf.erb', filename: order.txnid + ".pdf" ,                                  type: 'application/pdf', disposition:       'attachment', print_media_type: true))                  save_path = Rails.root.join('pdfs', order.txnid + ".pdf")                  File.open(save_path, 'wb') do |file|                    file << pdf                    filename = order.txnid + ".pdf"                  end                 file_name =  order.txnid + ".pdf"                 Invoice.upload(save_path, file_name)                end               end   

I am using wicked_pdf gem in gem file

I get the following error:

undefined method `render_to_string' for #<InvoiceJob:0x007ff05d8fbc68>  

Can someone help me rectify this.

why is devise not sending email via gmail smtp?

Posted: 29 Dec 2016 05:05 AM PST

I am using devise for authentication. It provides a forgot password link. When i send email then the email is not sent. Following is the settings i have used. Can you tell me why gmail is not sending the email? I have also turned on "allow less secure app to send email" and i have also enabled imap in gmail setting.

application.rb has the following setting.

ActionMailer::Base.smtp_settings = {        :address => 'smtp.gmail.com',    :domain => 'mail.google.com',    :port => 587,    :user_name => 'validemail@gmail.com',    :password => 'validpassword',    :authentication => 'login',    :enable_starttls_auto => true      }  

development.rb has

  config.action_mailer.default_url_options = { host: '127.0.0.1'}        config.action_mailer.delivery_method = :smtp  

After sending the email i get the following text in the console.

Devise::Mailer#reset_password_instructions: processed outbound mail in 215.2ms  Sent mail to validemail@gmail.com (1097.6ms)  Date: Thu, 29 Dec 2016 09:50:41 +0000  From: please-change-me-at-config-initializers-devise@example.com  Reply-To: please-change-me-at-config-initializers-devise@example.com  To: validemail@gmail.com  Message-ID: <5864dc7161acb_173921a07788707d@kofhearts-rubyonrails-3267120.mail>  Subject: Reset password instructions  Mime-Version: 1.0  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: 7bit    <p>Hello validemail@gmail.com!</p>    <p>Someone has requested a link to change your password. You can do this through the link below.</p>    <p><a href="http://127.0.0.1/users/password/edit?reset_password_token=WQxYad91mPghMxaurYA5">Change my password</a></p>    <p>If you didn't request this, please ignore this email.</p>  <p>Your password won't change until you access the link above and create a new one.</p>    Redirected to https://rubyonrails-kofhearts.c9users.io/users/sign_in  Completed 302 Found in 1965ms (ActiveRecord: 14.7ms)  

UPDATE:

I am just following this tutorial.

https://www.youtube.com/watch?v=ZEk0Jp2dThc

Send email is not working with the settings that are specified in this video.

Do rails has loading fixture function like django-extensions?

Posted: 29 Dec 2016 01:35 AM PST

I want to load some dummy data for test local development. How can I make it like django-script or django's fixture?

How to clear window variables when using turbolinks

Posted: 29 Dec 2016 01:03 AM PST

Using ruby on rails, I have code that is triggered with the following coffee script;

$ = jQuery  $(document).on "turbolinks:load", ->    if window.progress?      // execute code on a div with an id of ```target```  

On pages where the code is meant to trigger, I have a div with an id of target and a script tag which loads the progress parameter e.g.

<%= javascript_tag id: "window_vars" do %>    window.progress = <%= raw graph.data.to_json %>  <% end -%>  

If there is no turbolinks, then this works fine, the code triggers on the pages where it is meant to and does not trigger on the other pages. However, if I enable turbolinks 5.0.1 and I visit a page where the code is not meant trigger, then to a page where the code does trigger, and then back to the page where the code is not meant to trigger, the code triggers on the final page with an exception. It seems that turbolinks is not clearing the window.progress variable between page loads.

I have also tried testing for the present of the div with the target id, using $('target').length?, but the length is always 0, whether the id is on the page or not.

How to I prevent this code triggering on pages where it is not mean to trigger?

1 comment: