Sunday, August 28, 2016

Execute JS from Rails controller | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Execute JS from Rails controller | Fixed issues


Execute JS from Rails controller

Posted: 28 Aug 2016 07:33 AM PDT

I want to call a javascript file at a remote location ( Like CDN's ). I want to call that JS File from a controller and should be able to call functions of that JS file and capture the output. I know EXECJS can be used for that. I want to know how to specifically call a JS file on a remote location within the controller and execute functions.

I am following michael hartl ruby on rails tutorial chapter 8 List 8.19. My drop down manual is not working

Posted: 28 Aug 2016 07:08 AM PDT

This is my header.html.erb file I finished chapter 10 and the drop down manual still does not work. Please provide your suggestions. Thanks,

<header class="navbar navbar-fixed-top navbar-inverse">    <div class="container">      <%= link_to "sample app", root_path, id: "logo" %>      <nav>        <ul class="nav navbar-nav navbar-right">          <li><%= link_to "Home", root_path %></li>          <li><%= link_to "Help", help_path %></li>          <% if logged_in? %>              <li><%= link_to "Users", users_path %></li>            <li class="dropdown">              <a href="#" class="dropdown-toggle" data-toggle="dropdown">                Account <b class="caret"></b>              </a>              <ul class="dropdown-menu">                <li><%= link_to "Profile", current_user %></li>                 <li><%= link_to "Settings", edit_user_path(current_user) %></li>                <li class="divider"></li>                <li>                  <%= link_to "Log out", logout_path, method: "delete" %>                </li>              </ul>            </li>          <% else %>            <li><%= link_to "Log in", login_path %></li>          <% end %>        </ul>      </nav>    </div>  </header>  

Rails. stop database connection and reconnect

Posted: 28 Aug 2016 06:55 AM PDT

I try to implement a very easy backup process. Just dump the database into a file. The user gets all files displayed, choose one, and then the dump is loaded back. But loading back the dump is not possible while the rails server is running. How can I manage this? How can I stop the database connection, do my stuff and then reconnect to the database?

  • I have tried with postgresql and rake commands to dump the database and recover it -> Permission denied
  • I have tried with Sqlite3. Just copy the databasefile into a backup folder. But if I want to delete the current one to replace it with a new -> Permission denied
  • I have tried with Sqlite3 dump. I dumped the database but again I can only load the dump back if the rails server is not running.

There are libraries out like Yamldb which works, but this library only can save one backup. I have to save more then one and give them names.

I want to add resource's edit and new form on to active admin's dashboard: rails

Posted: 28 Aug 2016 06:49 AM PDT

I want to add resource's edit and new form on to active admin's dashboard. I tried all things that has been mentioned at documentation but it is not working. Some one help

Getting Duplicate records when returning search results with Ajax Rails

Posted: 28 Aug 2016 06:47 AM PDT

I have an app that has several invoices and users can search for specific invoices. I'm using Ajax so that users can make a search query.

The issue is when a user searches for invoice no."7289" it found the records but duplicate records.

Here's an screenshot as below;

screenshot.png

Here's the code as below;

index.js.erb

$('#kola tbody').empty();    <% if @shippingdetails.empty? %>  $('#kola tr').remove();  $('#kola tbody').append("No Results Found For Your Search...");  $("#kola tbody").css({"background-color": "white", "font-size": "100%", "font-weight": "900"});   <% else %>  <% @shippingdetails.each do |shippingdetail| %>  $('#kola tbody').append("<%= j render shippingdetail %>");  <% end %>  <% end %>  

index.html.erb

<div class="row">      <div class="col-md-5 col-md-offset-3">            <div class="table-responsive myTable">                <table id = "kola" class="table listing text-center">                  <thead>                      <tr class="tr-head">                          <td>Invoices</td>                      </tr>                  </thead>                      <a href="#" class="toggle-formed" style="float: right;" ><strong>Search</strong></a>                    <div id="sample">                        <%= form_tag shippingdetails_path, remote: true, method: :get, class: "form-group", role: "search" do %>                      <p>                          <center><%= text_field_tag :search, params[:search], placeholder: "Search for Invoices.....", autofocus: true, class: "form-control-search" %>                              <%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>                          </p>                          <% end %><br>                      </div>                          <tr>                          <td></td>                      </tr>                    <tbody>                                    <%= render @shippingdetails %>                  </tbody>                </table>          </div>      </div>  </div>  

_shippingdetail.html.erb

<tr class="tr-<%= cycle('odd', 'even') %>">        <td class="col-1"><%= link_to shippingdetail, shippingdetail %></td>    </tr>  

How can I prevent rails ajax from duplicating records?

Any suggestions are most welcome.

Thank you in advance.

devise_token_auth how to identify a use by token

Posted: 28 Aug 2016 06:29 AM PDT

I am new to use gem devise_token_auth and working on a mobile client api, two questions:

1) How should i identify a user? My current understanding is on a http request header set access_token is this right?

But seems from the source code i should provide for uid, access_token, clientlink uid = request.headers['did'] @token = request.headers['access-token'] @client_id = request.headers['client']

2) i can find a user.tokens like below:

 {"AOYZdDmwI7WQr8I6T4PpPw"=>{"token"=>"$2a$10$C/5f3JV7.9DZG8w.ggdCPelB6kzitWuGK4rfozHv15Hhf/x9DaCcO", "expiry"=>1473485374, "last_token"=>"$2a$10$abctsIP5bHPIm2nMXFTUH.1jPWQ5LiGTTrENjoqihWgcCkwRqbxb6", "updated_at"=>"2016-08-27T13:29:34.948+08:00"}}  

which is client and which is access-token?

Thank you!

ROR number_field_tag give error 'not a number'

Posted: 28 Aug 2016 07:13 AM PDT

enter image description here

Error Message

enter image description here

I'm trying to insert a number value through 'number_field_tag' but keep getting the same error message. Does anyone know what is causing this?

new.html.erb

<% provide(:title, 'Products') %>    <h1>Products</h1>  <div class="row">    <div class="col-md-6 col-md-offset-3">    <%= render 'shared/error_messages_p' %>        <%= form_for([:admin, @product], :html => {multipart:true}) do |f| %>          <%= f.label :title %>        <%= f.text_field :title, class: 'form-control' %>          <%= f.label :description %>        <%= f.text_area :description, :rows => 6, class: 'form-control' %>          <%= f.file_field :image %>          <%= number_field_tag :stock_quantity, 1, min: 1, class: "form-control" %>          <%= f.label :price %>        <%= f.text_field :price, class: 'form-control' %>          <%= f.submit "Create product", class: "btn btn-primary" %>        <% end %>    </div>  </div>  

products_controller.rb

class Admin::ProductsController < Admin::BaseController  before_action :set_product, only: [:show, :edit, :update, :destroy]  rescue_from ActiveRecord::RecordNotFound, with: :invalid_product    def index  @products = Product.all  end    def show  @product = Product.find(params[:id])  end    def new  @product = Product.new  end    def edit  end    def create  @product = Product.new(product_params)    if @product.save      redirect_to [:admin, @product], notice: 'Product was successfully created.'     else      render :new   end  end    def update      if @product.update(product_params)      redirect_to @product, notice: 'Product was successfully updated.'     else      render :edit   end  end    def destroy  @product.destroy    redirect_to products_url, notice: 'Product was successfully destroyed.'   end      private    def set_product    @product = Product.find(params[:id])  end    def product_params    params.require(:product).permit(:title, :description, :image, :price, :stock_quantity)  end    def invalid_product    logger.error "Attempt to access invalid cart #{params[:id]}"    redirect_to products_url, notice: 'Invalid product'  end      end  

product model

class Product < ActiveRecord::Base  attr_accessor :image  validates :title, :description, :image, presence: true  validates :price, numericality: {greater_than_or_equal_to: 0.01}  validates :title, uniqueness: true  validates :stock_quantity, numericality: { only_integer: true}  validates :image, allow_blank: true, format: {with: %r{\.(gif|jpg|png)\Z}i, message: 'must be a URL for GIF, JPG or PNG image.'}  mount_uploader :image, ImageUploader  

Bundle Install not working - Git permission denied

Posted: 28 Aug 2016 06:29 AM PDT

I try running my Ruby on Rails app on a local server using the terminal command 'Rails S' but I am then asked to bundle install all the gems on to this laptop - Osx

This is the terminal output:

Johns-MacBook-Pro-2:spu-test JohnSmith$ rails s  Could not find coffee-rails-4.0.1 in any of the sources  Run `bundle install` to install missing gems.  Johns-MacBook-Pro-2:spu-test JohnSmith$ bundle install  Fetching gem metadata from https://rubygems.org/  Fetching version metadata from https://rubygems.org/  Fetching dependency metadata from https://rubygems.org/  error: cannot open .git/FETCH_HEAD: Permission denied    Retrying git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca" due to error (2/4): Bundler::Source::Git::GitCommandError Git error: command `git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca"` in directory /Library/Ruby/Gems/2.0.0/bundler/gems/active_admin-3d7605f82706 has failed.  If this error persists you could try removing the cache directory '/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca'  error: cannot open .git/FETCH_HEAD: Permission denied    Retrying git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca" due to error (3/4): Bundler::Source::Git::GitCommandError Git error: command `git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca"` in directory /Library/Ruby/Gems/2.0.0/bundler/gems/active_admin-3d7605f82706 has failed.  If this error persists you could try removing the cache directory '/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca'  error: cannot open .git/FETCH_HEAD: Permission denied    Retrying git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca" due to error (4/4): Bundler::Source::Git::GitCommandError Git error: command `git fetch --force --quiet --tags "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca"` in directory /Library/Ruby/Gems/2.0.0/bundler/gems/active_admin-3d7605f82706 has failed.  If this error persists you could try removing the cache directory '/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca'  error: cannot open .git/FETCH_HEAD: Permission denied    Git error: command `git fetch --force --quiet --tags  "/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca"`  in directory /Library/Ruby/Gems/2.0.0/bundler/gems/active_admin-3d7605f82706 has  failed.  If this error persists you could try removing the cache directory  '/Users/JohnSmith/.bundle/cache/git/active_admin-d67faab65e9b74efbc8efb4a777a851e9f78b2ca'  Johns-MacBook-Pro-2:spu-test JohnSmith$  

ERROR using sudo bundle install after deleting the cache directory:

Johns-MacBook-Pro-2:spu-test JohnSmith$ sudo bundle install  Password:  Don't run Bundler as root. Bundler can ask for sudo if it is needed, and  installing your bundle as root will break this application for all non-root  users on this machine.  Fetching gem metadata from https://rubygems.org/  Fetching version metadata from https://rubygems.org/  Fetching dependency metadata from https://rubygems.org/  Rubygems 2.0.14.1 is not threadsafe, so your gems will be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.  Using rake 10.3.2  Using Ascii85 1.0.2  Using i18n 0.6.9  Using minitest 4.7.5  Using multi_json 1.10.1  Using thread_safe 0.3.4  Using tzinfo 0.3.39  Using builder 3.1.4  Using erubis 2.7.0  Using rack 1.5.2  Using mime-types 1.25.1  Using polyglot 0.3.5  Using sass 3.2.19  Using thor 0.19.1  Using coffee-script-source 1.7.0  Using execjs 2.1.0  Using activerecord-deprecated_finders 1.0.3  Using arel 4.0.2  Using bundler 1.12.5  Using hike 1.2.3  Using tilt 1.4.1  Using addressable 2.3.6  Using afm 0.2.1  Using aws_cf_signer 0.1.3  Using bcrypt 3.1.7  Using cancan 2.0.0.alpha from git://github.com/ryanb/cancan.git (at 2.0@e6bf4c8)  Using json 1.8.1  Using orm_adapter 0.5.0  Using excon 0.42.0  Using geocoder 1.2.4  Using gmaps4rails 2.1.2  Using hashery 2.1.1  Using pdf-core 0.1.6  Using ruby-rc4 0.1.5  Using ttfunk 1.1.1  Installing pg 0.17.1 with native extensions    Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.        /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb  checking for pg_config... yes  Using config values from /usr/local/bin/pg_config  checking for libpq-fe.h... yes  checking for libpq/libpq-fs.h... yes  checking for pg_config_manual.h... yes  checking for PQconnectdb() in -lpq... no  checking for PQconnectdb() in -llibpq... no  checking for PQconnectdb() in -lms/libpq... no  Can't find the PostgreSQL client library (libpq)  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby      --with-pg      --without-pg      --with-pg-config      --without-pg-config      --with-pg_config      --without-pg_config      --with-pg-dir      --without-pg-dir      --with-pg-include      --without-pg-include=${pg-dir}/include      --with-pg-lib      --without-pg-lib=${pg-dir}/      --with-pqlib      --without-pqlib      --with-libpqlib      --without-libpqlib      --with-ms/libpqlib      --without-ms/libpqlib      Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/pg-0.17.1 for inspection.  Results logged to /Library/Ruby/Gems/2.0.0/gems/pg-0.17.1/ext/gem_make.out  Using rails3_serve_static_assets 0.0.1 from git://github.com/heroku/rails3_serve_static_assets.git (at master@84910ce)  Using rails_log_stdout 0.0.1 from git://github.com/heroku/rails_log_stdout.git (at master@f9a9275)  Using underscore-rails 1.6.0  Using will_paginate 3.0.5  Using activesupport 4.0.5  Using rack-test 0.6.2  Using warden 1.2.3  Using rest-client 1.6.7  Using treetop 1.4.15  Using bourbon 3.2.3  Using coffee-script 2.2.0  Using sprockets 2.11.0  Using rdoc 4.1.1  Using uglifier 2.5.0  Using mandrill-api 1.0.53  Using pdf-reader 1.3.3  Using prawn 0.15.0  An error occurred while installing pg (0.17.1), and Bundler cannot continue.  Make sure that `gem install pg -v '0.17.1'` succeeds before bundling.  

Ruby: why instance eval on class creating instance method instead of class method

Posted: 28 Aug 2016 07:32 AM PDT

I want to create class method test dynamically and for that i am using define_method method inside instance_eval. I was expecting below code to create class method test but instead the code is creating instance method test. what could be the reason for this ?? below is my code.

module Accessor    def define_accessor_for_class(method)      self.instance_eval do        define_method :test do        end      end    end  end          class Employee    extend Accessor    define_accessor_for_class :name  end      Employee.name = "sanjay"  Employee.name    Employee.instance_methods(false) ==> [:test]  Employee.methods(false) => []  

Upload picture using angularjs and rails paperclip

Posted: 28 Aug 2016 05:47 AM PDT

I am u using paperclip in rails and angularjs, need to upload a picture when i upload a picture using rest client or postman it works but when i am send the picture abject which has all details about picture like name,type, size,base64 and all it is not working :(

so i tried this in rails console-

Student.last.update(picture: File.open("documents/app/images/abc.png"))  

it working in console but the issuee with this is i cannot get the path (absolute path) of the file , since the chrome blocks and adds fakepath for security reason.

Thanks

Rails 5 sever not running

Posted: 28 Aug 2016 04:54 AM PDT

I am getting this error while running command rails s

=> Booting Thin  => Rails 5.0.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  Exiting  /var/lib/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:90:in `<module:Session>': uninitialized constant Rack::Session::Abstract::Persisted (NameError)      from /var/lib/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:8:in `<module:ActionDispatch>'      from /var/lib/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/abstract_store.rb:7:in `<top (required)>'      from /var/lib/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/session/cookie_store.rb:2:in `<top (required)>'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/configuration.rb:181:in `const_get'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/configuration.rb:181:in `session_store'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/default_middleware_stack.rb:58:in `block in build_stack'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/default_middleware_stack.rb:13:in `tap'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/default_middleware_stack.rb:13:in `build_stack'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:504:in `default_middleware_stack'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:506:in `block in app'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:504:in `synchronize'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:504:in `app'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:37:in `block in <module:Finisher>'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'      from /usr/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'      from /usr/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'      from /usr/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'      from /usr/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'      from /usr/lib/ruby/2.2.0/tsort.rb:345:in `each'      from /usr/lib/ruby/2.2.0/tsort.rb:345:in `call'      from /usr/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'      from /usr/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'      from /usr/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'      from /root/sites/instagramm/config/environment.rb:5:in `<top (required)>'      from /root/sites/instagramm/config.ru:3:in `require_relative'      from /root/sites/instagramm/config.ru:3:in `block in <main>'      from /usr/lib/ruby/vendor_ruby/rack/builder.rb:55:in `instance_eval'      from /usr/lib/ruby/vendor_ruby/rack/builder.rb:55:in `initialize'      from /root/sites/instagramm/config.ru:in `new'      from /root/sites/instagramm/config.ru:in `<main>'      from /usr/lib/ruby/vendor_ruby/rack/builder.rb:49:in `eval'      from /usr/lib/ruby/vendor_ruby/rack/builder.rb:49:in `new_from_string'      from /usr/lib/ruby/vendor_ruby/rack/builder.rb:40:in `parse_file'      from /var/lib/gems/2.2.0/gems/rack-2.0.1/lib/rack/server.rb:318:in `build_app_and_options_from_config'      from /var/lib/gems/2.2.0/gems/rack-2.0.1/lib/rack/server.rb:218:in `app'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/server.rb:59:in `app'      from /var/lib/gems/2.2.0/gems/rack-2.0.1/lib/rack/server.rb:353:in `wrapped_app'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/server.rb:124:in `log_to_stdout'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/server.rb:77:in `start'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:90:in `block in server'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /var/lib/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from bin/rails:4:in `require'      from bin/rails:4:in `<main>'  

test devise_token_auth: Could not find devise mapping for path "/api/v1/auth"

Posted: 28 Aug 2016 04:26 AM PDT

I am trying to test create a user. Here is

registrations_controller_spec.rb

require 'rails_helper'    RSpec.describe DeviseTokenAuth::RegistrationsController, type: :controller do    before :each do      post :create, params:{email:"w@123.com",password:"123123",password_confirmation:"123123"}      @data = JSON.parse(response.body)    end      describe "Register a user" do      it "request should be successful" do        expect(response).to have_http_status(200)      end    end    end  

when i run the test i got:

Failures:      1) DeviseTokenAuth::RegistrationsController Register a user request should be successful       Failure/Error: post :create, params:{email:"w@123.com",password:"123123",password_confirmation:"123123"}         AbstractController::ActionNotFound:         Could not find devise mapping for path "/api/v1/auth".         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]       # ./spec/controllers/devise_token_auth/registrations_controller_spec.rb:5:in `block (2 levels) in <top (required)>'    Finished in 0.01477 seconds (files took 1.76 seconds to load)  1 example, 1 failure    Failed examples:    rspec ./spec/controllers/devise_token_auth/registrations_controller_spec.rb:10 # DeviseTokenAuth::RegistrationsController Register a user request should be successful  

The message provides two ways: 1) I tried to add the first into routes but not works, where or how should i add it. 2) I added @request.env["devise.mapping"] = Devise.mappings[:user] in before block but doesn't work.

How should i solve this? thank you!

Here's my routes.rb

Rails.application.routes.draw do      namespace :api do      scope :v1 do        mount_devise_token_auth_for 'User', at: 'auth'      end    end  end  

How to associate Rails models before one has saved

Posted: 28 Aug 2016 04:15 AM PDT

I am trying to build a blogging app and I'm using trix text editor and CarrierWave.

Trip editor allows you to drag images into the text area and I've managed to get image uploads working by posting images to their own BlogImages controller and model using the following code:

#blog_images_controller.rb:    def create    @image = BlogImage.create(image_params)    @image.image = params[:image]      respond_to do |format|      if @image.save        format.json { render :json => { url: @image.image.url } }      end    end  end    private  def image_params    params.require(:image).permit(:image)  end    #blog_images.coffee:    (->    host = undefined    uploadAttachment = undefined    document.addEventListener 'trix-attachment-add', (event) ->      attachment = undefined      attachment = event.attachment      if attachment.file        return uploadAttachment(attachment)      return    host = '/blog_images'      uploadAttachment = (attachment) ->      file = undefined      form = undefined      xhr = undefined      file = attachment.file      form = new FormData      form.append 'Content-Type', file.type      form.append 'image[image]', file      xhr = new XMLHttpRequest      xhr.open 'POST', host, true        xhr.upload.onprogress = (event) ->        progress = undefined        progress = event.loaded / event.total * 100        attachment.setUploadProgress progress        xhr.onload = ->        href = undefined        url = undefined        url = href = JSON.parse(@responseText).url        attachment.setAttributes          url: url          href: href        xhr.send form      return  ).call this  

My problem now is that I have a saved BlogImage but the blog which they need to be associated to hasn't yet been created, so I can't set this association up. I'm quite new to Rails so any guidance would be great.

devise session model name

Posted: 28 Aug 2016 05:08 AM PDT

In a Rails app, I'm using devise gem. I'm using Two model. For example A and B. The problem is When I login with one model, How can I know that which model I logged in? Is there any method that tells which model I logged in?

I tried method like

current_user  

But current_user DOES NOT exist when I logged in with another model. How can I know which model I logged in?

I tried like this:

<%= current_dpatient.email %><br>  <%= current_user.signed_in? %><br>  <%= Thread.current %><br>  

Deploy on heroku with s3 does not show images

Posted: 28 Aug 2016 06:49 AM PDT

enter image description hereI deployed my educational app in heroku(https://slobodalibrary.herokuapp.com). I've set s3 as a storage. But after some time images still disappear. What is the priobem? Where should I dig to fix it?

nested rails api with ember js (beginner)

Posted: 28 Aug 2016 03:18 AM PDT

First time poster and extremely new to ember js,rails and would describe myself as a beginner programmer.

I am currently using a nested rails api(and for the moment it cant be changed).It follows a pattern of:

   - apiHost/businesses returns all businesses     - apiHost/businesses/business_id returns the business with that id **     - apiHost/businesses/business_id/prices returns the prices in the business     - apiHost/businesses/business_id/prices/prices_id returns the price with the id **  

The ** shows the link which a PUT request can be sent to.

I am really struggling of finding a way to accesses the nested elements and from research ember js isn't a fan of nested resources.

I have come across a some websites which look promising but I just cannot seem to get it to work:http://thejsguy.com/2016/02/21/handling-nested-resources-in-ember-data.html (maybe my implementation is incorrect or code when doing return....) or I'm not sure of how to implement it Ember JS: Nested api routes

I have added my business model and the price model below.

export default DS.Model.extend({    address: DS.attr('string'),    description: DS.attr('string'),    price: DS.hasMany('price')   });    export default DS.Model.extend({    cost: DS.attr('string'),    description: DS.attr('string'),    business:DS.belongsTo('business')  });  

Any help would be greatly appreciated, the first link looks to be promising and perhaps the simplest solution for me.

I am currently using ember cli 2.7

Thank you.

Rails ajax request response

Posted: 28 Aug 2016 03:12 AM PDT

I am using Rails CoffeeScript to call an action in my controller, which is fine, but I can not get the response to work. I have a form with a list of budget lines. I want to allow the use to add a new line using CoffeeScript so I don't need to reload the question. I have got the following in CoffeeScript:

  $("button[id^='new_budget_line']").on 'click', (event) ->      category_id = $(this).attr('name')      child_economy_id = $('#child_economy_id').val()      $('#form_id').submit ->        valuesToSubmit = $(this).serialize()        $.ajax          type: 'POST'          url: $(this).attr('action')          data: valuesToSubmit          dataType: 'JSON'      $.ajax({        type: 'GET'        url: '../child_economy_lines/create_line'        data:          child_economy_id: child_economy_id          category_id: category_id          cost_type: 'direct'        dataType: JSON      }).done (response) ->        alert "Hey"        $('#test_append').html("Hey you now!!")  

And the following in my controller

  def create_line      logger.debug "Hejsa fra create line - category id #{params[:category_id]}"      @child_economy_line = @child_economy.child_economy_lines.build(:child_economy_category_id => params[:category_id], :cost_type => params[:cost_type])      if @child_economy_line.save        respond_to do |format|          format.js {render nothing: true}          format.json {render :json => "test"}        end      end    end  

The action in the controller i called fine, and the new line is created, but I can not the actions after the ajax call to work. The part from .done ...

Can anybody help me identify where it is going wrong?

Edit/update from activerecords "unpermited params"

Posted: 28 Aug 2016 05:19 AM PDT

I have an app that can allow proprietaire(name of user) to edit their campings(nome of post). Post have proprietaire_id. This part works.

I added some details on the camping (piscine, barbecue) in another table name caracteristiquetest. I made a relationship with camping_id. I can display value for piscine and barbecue. But when i try to allow proprietaire(user) to edit/update their camping, record not save and i have an error unpermited params.

How can i do this ?

Sorry for my english im french

camping_controller.rb

    def update          respond_to do |format|            if @camping.update(camping_params)              format.html { redirect_to @camping, notice: 'Camping was successfully updated.' }              format.json { render :show, status: :ok, location: @camping }            else              format.html { render :edit }              format.json { render json: @camping.errors, status: :unprocessable_entity }            end          end        end    def camping_params        params.require(:camping).permit(:name, :adresse, :code_postale, :commune, :courriel, :site_internet, :tel, :description, :nomdep, :nomregion, :numdep, :slug, :ville_id, :region_id, :departement_id, :latitude, :longitude, :etoile, :user_id, :image)        params.require(:caracteristiquetest).permit(:piscine, :barbecue)      end   

camping.rb

belongs_to :proprietaire  belongs_to :caracteristiquetest  accepts_nested_attributes_for :caracteristiquetest  

caracteristiquetest.rb

class Caracteristiquetest < ApplicationRecord    has_one :camping    accepts_nested_attributes_for :camping  end  

_form.html.erb

<%= f.select(:piscine, [['Non renseigné',"Non renseigné"], ['Oui',"Oui"], ['Non',"Non"]], {:selected => (@camping.caracteristiquetest.piscine?)}, {class:"form-control", id:"exampleSelect1"}) %>  

EDIT development.log

  Started GET "/campings/1" for 127.0.0.1 at 2016-08-28 14:06:56 +0200  Processing by CampingsController#show as HTML    Parameters: {"id"=>"1"}    [1m[36mCamping Load (1719.1ms)[0m  [1m[34mSELECT  "campings".* FROM "campings" WHERE "campings"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    [1m[36mCACHE (0.0ms)[0m  [1m[34mSELECT  "campings".* FROM "campings" WHERE "campings"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    Rendering campings/show.html.erb within layouts/application    [1m[36mCaracteristiquetest Load (0.0ms)[0m  [1m[34mSELECT  "caracteristiquetests".* FROM "caracteristiquetests" WHERE "caracteristiquetests"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    [1m[36mProprietaire Load (0.0ms)[0m  [1m[34mSELECT  "proprietaires".* FROM "proprietaires" WHERE "proprietaires"."id" = ? LIMIT ?[0m  [["id", 7], ["LIMIT", 1]]    [1m[36mCamping Load (1900.1ms)[0m  [1m[34mSELECT campings.*, (69.09332411348201 * ABS(campings.latitude - 48.52566299999999) * 0.7071067811865475) + (59.836573914187355 * ABS(campings.longitude - 3.664031) * 0.7071067811865475) AS distance, CASE WHEN (campings.latitude >= 48.52566299999999 AND campings.longitude >= 3.664031) THEN  45.0 WHEN (campings.latitude <  48.52566299999999 AND campings.longitude >= 3.664031) THEN 135.0 WHEN (campings.latitude <  48.52566299999999 AND campings.longitude <  3.664031) THEN 225.0 WHEN (campings.latitude >= 48.52566299999999 AND campings.longitude <  3.664031) THEN 315.0 END AS bearing FROM "campings" WHERE (campings.latitude BETWEEN 48.38093121688914 AND 48.67039478311084 AND campings.longitude BETWEEN 3.445496852835473 AND 3.8825651471645273 AND campings.id != 1) ORDER BY distance ASC[0m    [1m[36mProprietaire Load (1.0ms)[0m  [1m[34mSELECT  "proprietaires".* FROM "proprietaires" WHERE "proprietaires"."id" = ? ORDER BY "proprietaires"."id" ASC LIMIT ?[0m  [["id", 7], ["LIMIT", 1]]    Rendered campings/show.html.erb within layouts/application (2184.1ms)    Rendered campings/index.html.erb within layouts/application (19341.1ms)    Rendered devise/menu/_registration_items.html.erb (1.0ms)    Rendered devise/menu/_login_items.html.erb (1.0ms)    Rendered layouts/partials/_nav.html.erb (100.0ms)    Rendered layouts/partials/_messages.html.erb (1.0ms)    [1m[36mProprietaire Load (0.0ms)[0m  [1m[34mSELECT  "proprietaires".* FROM "proprietaires" WHERE "proprietaires"."id" = ? ORDER BY "proprietaires"."id" ASC LIMIT ?[0m  [["id", 7], ["LIMIT", 1]]    Rendered layouts/partials/_footer.html.erb (1.0ms)    Rendered devise/menu/_registration_items.html.erb (5.0ms)  Completed 200 OK in 8799ms (Views: 1524.3ms | ActiveRecord: 3620.2ms)        Rendered devise/menu/_login_items.html.erb (0.0ms)    Rendered layouts/partials/_nav.html.erb (75.0ms)    Rendered layouts/partials/_messages.html.erb (1.0ms)    Rendered layouts/partials/_footer.html.erb (1.0ms)  Completed 200 OK in 20182ms (Views: 19855.4ms | ActiveRecord: 2.0ms)      Started GET "/campings/1/edit" for 127.0.0.1 at 2016-08-28 14:07:08 +0200  Processing by CampingsController#edit as HTML    Parameters: {"id"=>"1"}    [1m[36mCamping Load (0.0ms)[0m  [1m[34mSELECT  "campings".* FROM "campings" WHERE "campings"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    [1m[36mProprietaire Load (0.0ms)[0m  [1m[34mSELECT  "proprietaires".* FROM "proprietaires" WHERE "proprietaires"."id" = ? ORDER BY "proprietaires"."id" ASC LIMIT ?[0m  [["id", 7], ["LIMIT", 1]]    Rendering campings/edit.html.erb within layouts/application    [1m[36mCaracteristiquetest Load (1.0ms)[0m  [1m[34mSELECT  "caracteristiquetests".* FROM "caracteristiquetests" WHERE "caracteristiquetests"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    Rendered campings/_form.html.erb (12.0ms)    Rendered campings/edit.html.erb within layouts/application (61.0ms)    Rendered devise/menu/_registration_items.html.erb (1.0ms)    Rendered devise/menu/_login_items.html.erb (1.0ms)    Rendered layouts/partials/_nav.html.erb (51.0ms)    Rendered layouts/partials/_messages.html.erb (0.0ms)    Rendered layouts/partials/_footer.html.erb (1.0ms)  Completed 200 OK in 487ms (Views: 463.3ms | ActiveRecord: 1.0ms)     Started PATCH "/campings/1" for 127.0.0.1 at 2016-08-28 14:07:18 +0200  Processing by CampingsController#update as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"1H6bsZ6d5Z8HVa0X8hUp0LQUg+SdU6CmqUEIrP7eSip0f3yVnzKlaPojwYz+AGS9a4wz4LtVeZU10G70TEIt2g==", "camping"=>{"name"=>"DOMAINE DE LA NOUE DES ROIS", "adresse"=>"rue machin", "code_postale"=>"10100", "commune"=>"ma commune", "courriel"=>"email@email.com", "site_internet"=>"www.exemple.com", "tel"=>"0101010101", "description"=>"ma description", "etoile"=>"3", "piscine"=>"Non"}, "commit"=>"Enregistrer", "id"=>"1"}    [1m[36mCamping Load (0.0ms)[0m  [1m[34mSELECT  "campings".* FROM "campings" WHERE "campings"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]    [1m[36mProprietaire Load (1.0ms)[0m  [1m[34mSELECT  "proprietaires".* FROM "proprietaires" WHERE "proprietaires"."id" = ? ORDER BY "proprietaires"."id" ASC LIMIT ?[0m  [["id", 7], ["LIMIT", 1]]  Unpermitted parameter: piscine  Completed 400 Bad Request in 5ms (ActiveRecord: 1.0ms)        ActionController::ParameterMissing (param is missing or the value is empty: caracteristiquetest):    app/controllers/campings_controller.rb:111:in `camping_params'  app/controllers/campings_controller.rb:82:in `block in update'  app/controllers/campings_controller.rb:81:in `update'    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.0ms)    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (1753.1ms)  

EDIT2

I added attr_accessor :piscine on camping.rb but i have same error

collection_select selection changes options for secondary collection_select?

Posted: 28 Aug 2016 05:39 AM PDT

When user_id is selected how can collection_select :challenge_id only show the challenges for that user_id instead of listing all the challenges?

<%= f.collection_select :user_id, User.order(:name),:id, :full_name, include_blank: true %>w    will  <%= f.collection_select :challenge_id, Challenge.order(:deadline),:id, :full_challenge, include_blank: true %>.  

UPDATE

<%= f.collection_select :user_id, User.order(:name),:id, :full_name, include_blank: true, id: "id_of_the_user_id_select_box" %>w    will  <%= f.collection_select :challenge_id, Challenge.order(:deadline),:id, :full_challenge, include_blank: true %>.    <script>    $( "#id_of_the_user_id_select_box" ).change(function() {         $.ajax({            type: "GET",            url: '<%= user_challenges_path %>',            data: {name: $('#id_of_the_user_id_select_box').prop('value')}         });    });  </script>  

challenges_controller

def user_challenges    # Not sure what to add in here  end  

Add references to a chosen column different from id

Posted: 28 Aug 2016 05:29 AM PDT

Is it possible to add references to a column different from the id column?

Usually when a relationship between two models (Model1 and Model2) is created, the use of model1:references and model2:references for the creation of the Relationship model automatically adds a model1_id and model2_id column (along with an index and a foreign key reference) for use in the model1/model2 association:

rails generate Relationship model1:references model2:references  

Say for instance Model1 = Teacher and Model2 = Pupil.
Suppose that Model2's records (pupils' records) are updated every now and then with a rake task: the values of its attributes (for instance name and school_credits) would change, preserving id and ranking (1 to 100).

Associate a teacher with a pupil_id would not have much sense.
Each teacher should be instead associated with his/her pupils' names using as a foreign key reference the attribute pupil.name instead of pupil.id.

Is that possible?
What options can I add to the command rails generate Relationship or what reference am I supposed to add to have this result?

collection_select show multiple object attributes?

Posted: 28 Aug 2016 02:32 AM PDT

In addition to showing the challenge's name. I also want to show its deadline next to the name.

It would look like this for example:

Visit London 09/09/16  Make $1,000,000 10/15/18  Knit a Scarf 01/11/19  

Instead of just this:

enter image description here

<%= f.collection_select :challenge_id, current_user.challenges.order(:deadline),:id,:name, include_blank: true %>  

how to expect 'render template' error

Posted: 28 Aug 2016 02:56 AM PDT

I have a view template "show.html.haml", something like

- if current_user.admin?    balabala  

It will get "undefined method `admin?' for nil:NilClass" while GET #show. I fixed it with " - if !current_user.nil? && current_user.admin?". And I want to add a test case with RSpec.

describe "before login user - " do      it "render the show template" do      book = FactoryGirl.create(:book)      get :show, id: book.id        expect(response).to render_template("show")      expect(response).to be_success    end  end  

While run "bin/rake spec", it always get success no matter if I add the condition "!current_user.nil?". How can I write the expect clause while I want to check if rendering 'show' view is sucess?

Rails Reverse Auction

Posted: 28 Aug 2016 01:20 AM PDT

I intend to build an app for reverse auction. I have been researching the way it can be done in Rails, but so far I could not come up with any realistic solution.

The procedure would be the following:

  • Reverse auction will start at a specific time for 3 minutes (count down), if any of the bidders makes a bid, the time will restart and count down start for 3 minute again, unless there are no further bids.

Any guidance how this can be done in rails? I assume this can be done using ActionCable, but maybe there is some other easier solution. I just can't seem to figure how to refresh the page to all bidders, if the new bid was made, so the count-down can start for 3 minutes again.

Thanks a lot in advance

Devise define routes and before_filter for users with admin attribute

Posted: 28 Aug 2016 01:35 AM PDT

I have an small app where I implemented devise. The model where I added Devise is consultant instead of user.

class Consultant < ApplicationRecord    devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :confirmable      def admin?      self.admin == true    end    end  

I also added an attribute like it suggest here the option 2 to identify admin users.

My goal is to achieve that only admin consultants have access everywhere. Consultants that are not admins should only have access to resources :tasks and get '/tasks/consultants/:id/worked', to: 'tasks#worked'. Visitors should be redirected to the sign_in.

For that purpose I am adding a before_filter in ApplicationController like this

class ApplicationController < ActionController::Base      before_filter :authenticate_admin!    skip_before_filter :authenticate_admin!, only: [:tasks]      private    def authenticate_admin!      current_consultant.try(:admin?)    end    end  

and in tasks_controller.rb I added this before_filter

class TasksController < ApplicationController    before_action :set_task, only: [:show, :edit, :update, :destroy]      before_filter :authenticate_consultant!      ...  

and my routes.rb is defined like this

Rails.application.routes.draw do      devise_for :consultants    devise_scope :consultant do      authenticated :consultant do        root 'tasks#index'      end        root to: "devise/sessions#new"    end      get '/home', to: 'static_pages#home'    get '/help', to: 'static_pages#help'      get   '/tasks/consultants/:id/worked', to: 'tasks#worked'      resources :tasks    resources :consultants    end  

I don't understand why is not validating the users, any user can access anywhere

Rails 5 Bootstrap 3 Modal Layout issue

Posted: 28 Aug 2016 01:58 AM PDT

I am using Rails 5 and Bootstrap 3 to build out an app, In this app I want Admins to be able to create and update users, to do so the create and update forms are held in bootstrap 3 Modals.

The modal is working, forms are working however there is a layout issue. The modal body and footer seem to be running together. I have checked to ensure all the divs have been closed off and they arrear to be, however the top div of the modal and its closing div dont seem to recognize each other.. I think the problem is with the modal #id when I remove the modal id it seems to work fine, whick leaves me to believe its the ruby in the id. (see below) is there any way to hack this out so it works?

Opening Modal Div with Ruby as part of the ID

<div class="modal fade" id="<%= "update_user#{user.id}" %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">  ...  </div>  

Full Modal Code

<div class="modal fade" id="<%= "update_user#{user.id}" %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">    <div class="modal-dialog" role="document">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>          <h4 class="modal-title" id="myModalLabel"><text id="pv_text_grn">PATROL</text><text id="pv_text_gry">VAULT</text> <i class="fa fa-pencil-square-o" aria-hidden="true"></i> Update <%= user.f_name %> <%= user.l_name %></h4>        </div>        <div class="modal-body">          <%= form_for(user, :method => :put, remote: true) do |f| %>          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">            <div class="row">              <div class="col-xs-12">                <div class="field">                  <%= f.label :email, "Email" %><br />                  <%= f.email_field :email, :class => 'form-control' %>                </div>              </div>            </div>            <div class="row">              <div class="col-xs-12 col-sm-6">                <div class="field">                  <%= f.label :password %>                  <%= f.password_field :password, autocomplete: "off", :class => 'form-control', :placeholder => '* * * * * *' %>                </div>              </div>              <div class="col-xs-12 col-sm-6">                <div class="field">                  <%= f.label :password_confirmation %><br />                  <%= f.password_field :password_confirmation, autocomplete: "off", :class => 'form-control', :placeholder => '* * * * * *' %>                </div>              </div>            </div>            <div class="row">              <div class="col-xs-12 col-sm-6">                <div class="field">                  <%= f.label :f_name, "First Name" %><br />                  <%= f.text_field :f_name, disabled: true, :class => 'form-control' %>                </div>              </div>              <div class="col-xs-12 col-sm-6">                <div class="field">                  <%= f.label :l_name, "Last Name" %>                  <%= f.text_field :l_name, disabled: true, :class => 'form-control' %>                </div>              </div>            </div>            <div class="row">              <div class="col-xs-12">                <div class="field">                  <%= f.label :primary_tel, "Telephone" %>                  <%= f.text_field :primary_tel, :class => 'form-control' %>                </div>              </div>            </div>            <div class="row">              <div class="col-xs-6">                <div class="field">                  <%= f.label :role_id %><br />                  <%= collection_select(:user, :role_id, Role.all, :id, :name, {prompt: true}) %>                </div>              </div>            </div>          </div>        </div>        <div class="modal-footer">          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>          <%= f.submit "Update User", :class => 'btn btn-primary' %>        </div>        <% end %>      </div>    </div>  </div>  

Image Of Modal

enter image description here

You can see that the dividing line that should be at the footer is now for some reason at the top just below the email label.

Any assistance here would be a great help.

-> The reason I am using the user.id in the modal id is to create unique modal id's as there are several users.

Controller action for 'adding' a Post to a Collection model? [Rails]

Posted: 27 Aug 2016 11:50 PM PDT

So I have these three models - Post, User, Collection, where a user has many posts and a collection belongs to a user and has many posts. A post can be in more than one collection too. Here are the codes:

user.rb

class User < ActiveRecord::Base      has_many :posts, dependent: :destroy    has_many :collections, dependent: :destroy  end  

post.rb

class Post < ActiveRecord::Base      belongs_to :user    has_many :collectables    has_many :collections, through: :collectables  end  

collection.rb

class Collection < ActiveRecord::Base    belongs_to :user    has_many :collectables    has_many :posts, through: :collectables  end  

collectable.rb

class Collectable < ActiveRecord::Base    belongs_to :post    belongs_to :collection  end  

Now, I have a '+' icon on every post, clicking on which a modal will pop up listing the current user's collections where you can just click on a collection name and that post will automatically get added to that collection. So, how should this 'adding' occur in the controller? I would've known the steps if I were creating a new post with the association, but how do I add an already existing post? Right now I'm using << to append the post to @collection.posts but is that the right way? The downside is that when I'm on the Collection show page, I cannot order the posts by the time they were added to that collection.


For the curious, here's what my code looks like right now:

_post.html.haml

= link_to posts_path(foo_param: post.id), remote: true, id: "add-collection-button" do         <i class="zmdi zmdi-plus add_post_button title="Add to collection"></i>  

^This is the like button. It sends the id of that particular post as a param which we'll need later:

add_to_collection.html.haml

= render 'add'  

_add.html.haml

- if current_user.collections.count > 0    %h2.add-to-collection Add to Collection      .collection-list        - current_user.collections.all.each do |collection|          = link_to add_to_collection_posts_path(foo: collection.id, post: params[:foo_param]), id: "add_link", remote: true do            .collection_item              = collection.name  

^This is the partial that'll be rendered in the modal. Here again, clicking on a collection name sends that particular collection's id as a param along with the previously collected post.id param:

index.html.haml

#myModal.modal.fade{"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}    .modal-dialog{:role => "document"}      .content  

index.js.erb

$(".content").html("<%= escape_javascript(render 'posts/add') %>");  $('#myModal').modal('show');  

^The modal itself followed by the js to render the partial in the modal upon clicking on the '+' icon.

posts-controller.rb

def add_to_collection    if params[:foo].present?      @collection = Collection.find(params[:foo])      @post = Post.find(params[:post])      if !@collection.posts.include? @post        @collection.posts << @post        @collection.save      end    end      respond_to do |format|      format.html      format.js    end  end  

^And finally, this is where the adding takes place. I know that this code looks like spaghetti and I'm sure that there are better and more efficient ways of doing this but as a rails beginner, this is all I could come up with. So what would be a better way of handling this? Thanks in advance!

Angular 2 and ActionCable integration

Posted: 28 Aug 2016 06:19 AM PDT

I'm trying to make a Angular2 app (bootstrapped with angular-cli) work with Rails's ActionCable by integrating this lib on the frontend https://github.com/mwalsher/actioncable-js

I npm installed the lib,

added this to angular-cli-build.js

'actioncable-js/index.js',  

and this in system-config.ts:

/** Map relative paths to URLs. */  const map: any = {    'moment': 'vendor/moment/moment.js',    'ng2-bootstrap': 'vendor/ng2-bootstrap',    'lodash': 'vendor/lodash',    'actioncable-js': 'vendor/actioncable-js'  };    /** User packages configuration. */  const packages: any = {      'ng2-bootstrap': {      format: 'cjs',      defaultExtension: 'js',      main: 'ng2-bootstrap.js'      },    'actioncable-js':{      main: 'index.js'    },    'moment':{      format: 'cjs'    },    'lodash':{      main: "lodash.js"    }  };  

added this to my component:

import { ActionCable } from 'actioncable-js';  

but the build errors with this message:

Cannot find module 'actioncable-js'.

anyone has any idea why?

My guess is typings are missing, but I'm not sure how to fix this.

Use MySQL workbench to create tables and data for rails app

Posted: 27 Aug 2016 11:10 PM PDT

Can I use MySQL Workbench to create the tables and add data then import / connect that into my Rails app? My Rails app is already connected to MySQL. I am just wondering if I create tables in MySQL Workbench through the app_development schema if that will sync over to my Rails project or not and if there's a way to check to see if it worked?

where best to calculate and create a large table to be shown in view?

Posted: 27 Aug 2016 11:45 PM PDT

Based on a couple of fields in the ActiveRecord I need to do a series of calculations which will result in displaying a table (in the View) with around 10 columns and 15 rows.

I don't want to do these calculation in the View so I thought about creating a 2D Array to store the rows in the Model and then just access this array in the View to build a table to show. However it seems I cannot store an Array in a Model's instance variable so am looking for suggestions on how to best handle this situation?

If there is a way to pass an Array from the Model to the View this would solve my problem. Tried something like this but didnt work due to attr_accessor not handling arrays?

Model xxx

attr_accessor :row_hash  after_initialize do      makeTable  end  def makeTable      row_hash = Array.new      for i in 1..15 do          row_hash.push(i)      end  end  

View

<% @xxx.row_hash.each do |r| %>   <%= r %>   <% end %>  

The row_hash populates ok in the Model but I get 'no method defined each' in the view

Rails only pass params that have changed on edit submit

Posted: 28 Aug 2016 07:20 AM PDT

I have a edit form that prepopulates with the current values. Its a custom edit screen (not the default one that rails uses) and what Im using it for is for users to submit changes that will get voted on and might eventually get applied to the record. However, in the time it takes to be voted on something else might have changed and I dont want to overwrite the changes if they didnt submit a change.

EDIT: Changing to my more specific case so hopefully answers will work for it...

I have the following tables: Recipes, RecipeIngredients, RecipeSteps, RecipeChanges. On the show view of my recipes it displays all the ingredients/steps and there is a tab that then changes just the ingredients/steps to forms as to allow the user to submit changes. I dont want these changes applied though. Instead Im trying to create a voting system where people can vote on them. So what I have decided on is to convert the parameters from the form into a json string and save it in the RecipeChanges table under a single column (instead of using two table for ingredient changes and step changes). Heres the code for the form (html removed to make it easier to see the rails stuff):

<%= form_for @recipe, url: recipe_recipe_changes_path(@recipe), html: {method: "post"}, remote: true do |f| %>      <%= f.fields_for :recipe_ingredients, f.object.recipe_ingredients.order(:order) do |ff| %>          <%= ff.hidden_field :order, class: "position" %>          <%= ff.text_field :ingredient, placeholder: "Add Ingredient (e.g. 3 cups cooked rice)" %>          <label><%= ff.check_box :_destroy %>Remove</label>       <% end %>      <%= f.fields_for :recipe_steps do |ff| %>          <%= ff.hidden_field :order, class: "position"%>          <%= ff.text_area :step %>          <label><%= ff.check_box :_destroy %>Remove</label>       <% end %>      <%= submit_tag "Submit", class: "button" %>  <% end %>  

So this sends a recipe object to my RecipeChange controller and there I handle the params to save them as the json string like so:

def create      @change = RecipeChange.new      @change.recipe_id = params[:recipe_id]      @change.new_recipe = recipe_change_params.to_json      #if @change.save        #add alert for successfully adding      #else        # add code for error handling      

No comments:

Post a Comment