Monday, October 31, 2016

Rails user login is nil | Fixed issues

Rails user login is nil | Fixed issues


Rails user login is nil

Posted: 31 Oct 2016 07:39 AM PDT

I have my rails app and when I try to login (I have created user called "test") I see this in the console:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"tlKwtMBNJ4LzJuJq13bUscAGpumdr+HVmUlGlfIudT9032DMXNxqa0d2VCxCvDZRDe1D6pFfaTafSRiL6tUvhw==", "session"=>{"login"=>"", "password"=>"[FILTERED]"}, "commit"=>"Log in"}    User Load (1.7ms)  SELECT  `users`.* FROM `users` WHERE `users`.`login` IS NULL LIMIT 1  

I see that in the session parameters application can't get user login (and maybe password too). Below are my user and session controllers:

class UsersController < ApplicationController      before_action :require_admin      def new          @users = User.new      end      def create          @user = User.new(user_params)          if @user.save               session[:user_id] = @user.id               current_user = @user.id                redirect_to @user          else               redirect_to '/login'           end       end      private      def user_params          params.require(:user).permit(:first_name, :last_name, :email, :login)      end  end  

Session controller:

class SessionsController < ApplicationController        def new      end        def create          @user = User.find_by_login(params[:login])          if @user && @user.authenticate(params[:password])              session[:user_id] = @user.id              redirect_to '/'          else               flash[:error] = 'err'              redirect_to '/login'          end      end        def destroy          session[:user_id] = nil           redirect_to root_url      end  end  

I have also tested the user creation and the record is in the database.

Get attribute values at beginning and end of a date range

Posted: 31 Oct 2016 07:45 AM PDT

I have a database table stockmovements with columns DATE, PRODUCT, UNITS,TYPE, STOCK. STOCK saves the value of stock at that date when a certain stock movement was done. TYPE can be purchase or sold or return.

I group by product so that any row of the table in my view shows a product. Then I want to create 2 columns. Stock start and stock end. Showing stock values at the first and last date of a date range. So that later let say I apply I filter 1st october - 31st october the 2 columns will show stock value at 1st october and stock value at 31st october.

If no filters are applied columns will show stock value of earliest and latest stockmovement among all values in database.

And in the middle columns to show units for each stockmovement type. So that in the end will be product, stock start, purchased, sold, returned, stock end. This is just to give an idea about the general logic but it doesn't really matter for the question.

I have this in my controller:

@stockmovements = Stockmovement.all.group(:PRODUCT)  

What should I add to my view:

 <td><%= number_to_human stockmovement.STOCK, precision: 0 %></td>  

to get the stock values at beginning and end of the date range? Or should this be done in the model? I basically need STOCK where DATE= start date and STOCK where DATE= end date. But I can't find any helper to do that.

rolify (n+1) issue using with_role

Posted: 31 Oct 2016 07:17 AM PDT

facing issue of n+1 problem

my controller code

def index @merchants = Merchant.includes(users: [:users_roles]) .page(params[:page]).per(10) end

on view @merchants.each do |m| admins = m.users.with_role('merchant')

it is fetching 10 queries while listing

Edit comment , nested form through Zurb Reveal - Rails

Posted: 31 Oct 2016 07:08 AM PDT

First of all this is the error

First argument in form cannot contain nil or be empty  

What I have is a Thread model and controller and a Answer model and Controller. And what I am trying to do is edit the answer on the show page of the thread via a zurb Reveal Modal.

and this what my code looks like

Thread Modal

class Thread < ApplicationRecord    belongs_to  :user    has_many    :answers      extend FriendlyId    friendly_id :subject, use: :slugged  end  

Answer Model

class Answer < ApplicationRecord    belongs_to  :user    belongs_to  :thread  end  

Answer Controller

def edit      @thread = Thread.friendly.find(params[:thread_id])      @answer = @thread.answers.find(params[:id])      render :layout => false  end    def update      @thread = Thread.friendly.find(params[:thread_id])      @answer = @thread.answers.find(params[:id])      respond_to do |format|          if @answer.update(params[:answer].permit(:content))              format.html { redirect_to thread_path(@thread) }              format.json { render :show, status: :ok, location: @answer }          else              format.html { redirect_to @thread, alert: "Unable to save your post" }              format.json { render json: @answer.errors, status: :unprocessable_entity }          end      end  end  

Show Thread

<%= render @thread.answers %>  

Answer Partial

<% if current_user.present? && current_user.id == answer.user_id %>  <ul class="edit-links pull-right">      <li>            <%= link_to 'Edit', edit_thread_answer_path(answer.thread, answer), :remote => true, class: "edit", "data-open" => "editModal", "data-open-ajax" => edit_thread_answer_path(answer.thread, answer) %>      </li>      <li>          <%= link_to 'Destroy', [answer.thread, answer], method: :delete, data: { confirm: 'Are you sure?' }, class: "destroy" %>      </li>  </ul>    <% end %>  <p>      <%= simple_format answer.content %>  </p>    <div id="editModal" class="reveal" data-reveal>      <%= render :partial => 'answers/edit_form' %>      <button class="close-button" data-close aria-label="Close modal" type="button">          <span aria-hidden="true">&times;</span>      </button>  </div>  

Answer Edit Form Partial

<h1>Edit Answer</h1>    <%= form_for([@thread, @answer]) do |f| %>        <%= f.text_area :content, :rows => "10" %>        <%= f.submit "Update", :class => "button add-thread" %>  <% end %>  

I get the error when I try to open a thread#show

its says the error is here

ArgumentError in Threads#show  <%= form_for([@thread, @answer]) do |f| %>  

Trace of template inclusion: app/views/answers/_answer.html.erb, app/views/threads/show.html.erb

Any suggestions ? where may the error be ?

How to create delayed complex objects creation

Posted: 31 Oct 2016 07:38 AM PDT

I got this problem: I have a complex model, Recipe, which have_many Ingredients, belongs_to User, have paperclips images.

I attempt to create some base objects for each new User. For example: a recipe, with it's ingredients (which are differents for each User). How to create a job to handle these recipes creations? knowing that they must be editable by their users, etc. It's easy for a basic model with no relationships but I'm blocked here...

-I don't want to create Ingredients or Recipe for all users, I want them to be able to delete them.

Here are the params for a single recipe creation by a random user :

Parameters: {"utf8"=>"✓", "recipe"=>{"name"=>"Recipe test", "category"=>"Chocolate", "owner"=>"Tom", "baking"=>"100", "note"=>"",  "quantities_attributes"=>{"0"=>{"ingredient_id"=>"6434", "weight"=>"100", "_destroy"=>"false"}, "1"=>{"ingredient_id"=>"6681", "weight"=>"10", "_destroy"=>"false"}, "2"=>{"ingredient_id"=>"6668", "weight"=>"210", "_destroy"=>"false"}, "3"=>{"ingredient_id"=>"6591", "weight"=>"100", "_destroy"=>"false"}, "4"=>{"ingredient_id"=>"6611", "weight"=>"20", "_destroy"=>"false"}, "5"=>{"ingredient_id"=>"", "weight"=>"", "_destroy"=>"false"}},  "process"=>"<p>This is a f*** test of recipe recipe creation</p>\r\n\r\n<p><img alt=\"\" height=\"26\" src=\"http://localhost:3000/assets/ckeditor/plugins/smiley/images/Emoji Smiley-109.png\" title=\"\" width=\"26\" /></p>\r\n"},   "commit"=>"SUBMIT"}  

Any idea ?

Rails assosiations routing

Posted: 31 Oct 2016 07:04 AM PDT

I have two models Blog and User with following association

Blog belongs_to :user  

My routes are as follows

resources :users, shallow: true do    resources :blogs  end  

These are the routes generated

   user_blogs GET    /users/:user_id/blogs(.:format)     blogs#index                POST   /users/:user_id/blogs(.:format)     blogs#create  new_user_blog GET    /users/:user_id/blogs/new(.:format) blogs#new      edit_blog GET    /blogs/:id/edit(.:format)           blogs#edit           blog GET    /blogs/:id(.:format)                blogs#show  

The question is why some routes ( new_user_blog for example) has the right routing, but others (edit_blog should be edit_user_blog) are wrong?

Rails 5 - Cannot initialize ActionCable

Posted: 31 Oct 2016 06:33 AM PDT

I just upgraded my app to Rails 5, I'm following a tutorial about ActionCable basics, but I cannot start a server.

Everytime I try to do so, I get the following error:

uninitialized constant ActionCable (NameError)

It seems like it comes from my routes.rb file, from this line :

mount ActionCable.server => '/cable'

This line is specified in every tutorial I've read so far, so I assume it is required for Actioncable to work. Has anyone encountered this problem before ? My gemfile is up-to-date, i'm using rails 5.0.0.1

Rails: Still confused about SQL Injection

Posted: 31 Oct 2016 06:12 AM PDT

I've made some posts about translating user input from a search box into an ActiveRecord Parameterized statement, which may be vulnerable to SQL injection, but I think I may have a solution.

Here's how the search works. The user enters something like this into the search box:

name="hello" AND NOT address.town="Villa"  

Internally, I convert it to:

query = ["name LIKE ? AND address.town NOT LIKE ?", "hello", "villa"]  

for:

if search    query = convert_search_to_query search    begin      includes(:address).where(query)    # rescue Exception ...  ...  ...  

Here's my idea: simply check the user-inputted attributes ("name", "address.town" in this case) to make sure it's an exact match for the acceptable list of user attributes.

If I were to do this, I think that there would be no SQL Injection possible since I am using parameterized statements (with the '?') to handle the only part of the user's input I can't check -- the values he entered for each attribute.

Based on what I read from other posts on here, I don't see how this code could be any more vulnerable than a normal parameterized search, but I don't have a lot of experience with SQL injection. Is it vulnerable?

Also:

I understand that there are plugins that may be able to help, but what I want to do is really very simple, and is already working, and I'd rather keep my app as lightweight as possible.

Google Adsense, CORS and Rails in Safari dumps thousands of console errors

Posted: 31 Oct 2016 06:23 AM PDT

I am serving google ads on a ssl site successfully, with CORS headers set properly (and wide open) by rack-cors as:

Rails.configuration.middleware.insert_before 0, Rack::Cors do    allow do      origins  '*'      resource '*', headers: :any, methods: :any    end  end  

I can confirm that the headers are there with a curl call:

$ curl -I https://viewing.nyc -H "Origin: https://foobar.com"  ...  Access-Control-Allow-Origin: https://foobar.com  Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS  Access-Control-Max-Age: 1728000  ...  

If you visit in Chrome or Firefox, there are no cross site scripting errors in the console, yet on Safari, there are thousands.

Blocked a frame with origin "https://googleads.g.doubleclick.net" from accessing a frame with origin "https://viewing.nyc". Protocols, domains, and ports must match.  

Live example

I've poured through the rack-cors issues page with no solution working thus far. Why is this happening only on Safari, and how can I fix it?

Rails foreign key confusion

Posted: 31 Oct 2016 06:20 AM PDT

I'm trying to learn rails. I have 2 tables Users and Posts, I want to link the email address from Users to Posts but I'm not sure how to go about it.

I have pre-made the table but how to I go about adding a Users.email to the new select box, so far I have this in the index.html.erb.

 <tbody>      <% @posts.each do |post| %>        <tr>          <td><%= post.title %></td>          <td><%= post.time %></td>          <td><%= post.body %></td>          <td><%= post.user_id %></td>          <td><%= link_to 'Show', post %></td>          <td><%= link_to 'Edit', edit_post_path(post) %></td>          <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>  

And this in my form.html.erb

%= form_for(post) do |f| %>    <% if post.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>          <ul>        <% post.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>      <div class="field">      <%= f.label :title %>      <%= f.text_field :title %>    </div>      <div class="field">      <%= f.label :time %>      <%= f.datetime_select :time %>    </div>      <div class="field">      <%= f.label :body %>      <%= f.text_area :body %>    </div>      <div class="field">      <%= f.label :user_id %>      <%= f.number_field :user_id %>    </div>      <div class="actions">      <%= f.submit %>    </div>  <% end %>  

As you can see I have a user_id field but how would I go about linking that to the primary key of Users? and then to do and email lookup? Thanks.

A field should not be present if according to an enum

Posted: 31 Oct 2016 07:06 AM PDT

I have an enum status:

enum status: [ :x, :y , :z ]  

Each status has model attributes that only relate to the selected status.

How would I validate that if the status is 'x' that the attributes related to 'y' and 'z' are blank? And simiar validations are needed for status 'y' and status 'z'.

I want to validate that only the fields (attributes) that relate to the selected status are present.

Multidomain Routing, with same routing names

Posted: 31 Oct 2016 05:29 AM PDT

constraints DomainRouting.new("other.local") do      devise_for :users, controllers: { registrations: "registrations" }      get "/*permalink",  to: "mods#show",       as: :mod, constraints: ModConstraint.new(:other)      root to: "categories#index"    end      constraints DomainRouting.new("something.local") do      scope "something" do         devise_for :users, controllers: { registrations: "registrations" }        get "/*permalink",  to: "mods#show",       as: :mod, constraints: ModConstraint.new(:something)        root to: "categories#index"      end    end  

how can i achieve the following scenario? ArgumentError: Invalid route name, already in use: 'new_user_session' (same goes for mods_path)

we need other.local/:permalink and something.local/something/:permalink

(and +8 other domains, with different routings (but same controllers))

Rails + Materialize + turbolinks takes longer time for asset precompile

Posted: 31 Oct 2016 05:34 AM PDT

I'm using Rails 4.2 and materialize-sass gem for materialized UI. In the production environment, it takes nearly 10min for asset precompiling. Is there any way to reduce the time. I have used turbolinks in my application. I have disabled turbolinks based on controller as,

In application_helper.rb

def get_access_to_turbolinks      controllers = ["home", "pages"]      if controllers.include? params[:controller]          return "data-turbolinks='true'"      else          return "data-turbolinks='false'"      end  end  

In application.html.erb

<body <%= get_access_to_turbolinks.html_safe %>">  

Data-turbolinks becomes false in the HTML code and even then the page is not loading as normal, instead it is rendering. Also I have provided some initializer for select, dropdown inside the function called $.fn.initialise_me(). This function has been called inside the following,

$(document).ready(function(){      $.fn.initialise_me();     });    document.addEventListener("turbolinks:load", function() {      $.fn.initialise_me();     });  

NoMethodError though method has been defined

Posted: 31 Oct 2016 05:28 AM PDT

I have a Ruby On Rails weblog application and am getting a NoMethodError in PostsController#show issue when opening a post. PostsController is stored under rails/weblog/app/controllers

I get undefined method 'set_current_page' for #<PostsController:0x007fb162831e70> however set_current_page is defined like so:

  private      def set_current_page         @current_page = params[:page] || 1      end  end  

and then used in a before_action

before_action :set_current_page, except: [:index]  before_action :set_post, only: [:show, :edit, :update, :destroy]  

Full stack trace:

activesupport (5.0.0.1) lib/active_support/callbacks.rb:382:in `block in make_lambda'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:150:in `block (2 levels) in halting_and_conditional'  actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:12:in `block (2 levels) in <module:Callbacks>'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `block in call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `each'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'  actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'  activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument'  activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'  activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument'  actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'  activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'  actionpack (5.0.0.1) lib/abstract_controller/base.rb:126:in `process'  actionview (5.0.0.1) lib/action_view/rendering.rb:30:in `process'  actionpack (5.0.0.1) lib/action_controller/metal.rb:190:in `dispatch'  actionpack (5.0.0.1) lib/action_controller/metal.rb:262:in `dispatch'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'  rack (2.0.1) lib/rack/etag.rb:25:in `call'  rack (2.0.1) lib/rack/conditional_get.rb:25:in `call'  rack (2.0.1) lib/rack/head.rb:12:in `call'  rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'  rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'  activerecord (5.0.0.1) lib/active_record/migration.rb:552:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'  web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app'  web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call'  web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch'  web-console (3.4.0) lib/web_console/middleware.rb:18:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'  railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'  sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'  rack (2.0.1) lib/rack/method_override.rb:22:in `call'  rack (2.0.1) lib/rack/runtime.rb:22:in `call'  activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'  railties (5.0.0.1) lib/rails/engine.rb:522:in `call'  puma (3.6.0) lib/puma/configuration.rb:225:in `call'  puma (3.6.0) lib/puma/server.rb:578:in `handle_request'  puma (3.6.0) lib/puma/server.rb:415:in `process_client'  puma (3.6.0) lib/puma/server.rb:275:in `block in run'  puma (3.6.0) lib/puma/thread_pool.rb:116:in `block in spawn_thread'  

The posts_controller.rb file:

class PostsController < ApplicationController      before_action :set_current_page, except: [:index]      before_action :set_post, only: [:show, :edit, :update, :destroy]        # GET /posts      # GET /posts.json      def index          @posts = Post.paginate(page: params[:page],                              per_page: params[:per_page])                              .order('title, user_id')      end        # GET /posts/1      # GET /posts/1.json      def show      end        # GET /posts/new      def new          @post = Post.new      end        # GET /posts/1/edit      def edit      end        # POST /posts      # POST /posts.json      def create          @post = Post.new(post_params)          @post.user = User.find_by email: params[:email]            respond_to do |format|              if @post.save                  format.html { redirect_to (post_url(@post, page: @current_page)), notice: 'Post was successfully created.' }                  format.json { render :show, status: :created, location: @post }              else                  format.html { render :new }                  format.json { render json: @post.errors, status: :unprocessable_entity }              end          end      end        # PATCH/PUT /posts/1      # PATCH/PUT /posts/1.json      def update          @post.user = User.find_by email: params[:email]          respond_to do |format|              if @post.update(post_params)                  format.html { redirect_to (post_url(@post, page: @current_page)), notice: 'Post was successfully updated.' }                  format.json { render :show, status: :ok, location: @post }              else                  format.html { render :edit }                  format.json { render json: @post.errors, status: :unprocessable_entity }              send          end      end        # DELETE /posts/1      # DELETE /posts/1.json      def destroy          @post.destroy          respond_to do |format|              format.html { redirect_to posts_url(page: @current_page), notice: 'Post was successfully destroyed.' }              format.json { head :no_content }          end      end        private          # Use callbacks to share common setup or constraints between actions.          def set_post              @post = Post.find(params[:id])          end            def set_current_page              @current_page = params[:page] || 1          end            # Never trust parameters from the scary internet, only allow the white list through.          def post_params              params.require(:post).permit(:title, :body, :page)          end      end  end  

how to pass Constraint variables into helpers

Posted: 31 Oct 2016 05:50 AM PDT

We host a multi-domain environment and use constraints for the routing, to decide which domain it is.

constraints DomainRouting.new("something.local", "something.com") do      devise_for :users, controllers: { registrations: "registrations" }      scope "mods" do        defaults game: "mygame" do          get "/*permalink",  to: "mods#show",       as: :mod, constraints: ModConstraint.new(:something)          get "/*permalink",  to: "categories#show", as: :category, constraints: CategoryConstraint.new(:something)            end        root to: "categories#index"      end      get "/", to: redirect("/mods")    end  

how can i call category_path(cat) let's say in a mailer, where we don't have any request object available?

so we need to be able to call that path for the correct domain, but i can't figure a way to do.

rails5

rails heroku db:seed not going through

Posted: 31 Oct 2016 04:56 AM PDT

I recently destroyed my Player model, and generated a User model, with pretty much the same fields except the User one has username:string, email:string, password:digest.

I also have a Blog model which is in a one-to-many relationship with the User model (previously with the Player model).

class User < ApplicationRecord    has_many :blogs, dependent: :destroy  end    class Blog < ApplicationRecord    belongs_to :user  end  

Problem is, on Heroku console, the Blog model still has player_id field from before.

Blog(id: integer, player_id: integer, content: text, created_at: datetime, updated_at: datetime)  

I can run heroku run rails db:migrate, but when I try to run heroku run rails db:seed, it gives me this error.

ActiveModel::MissingAttributeError: can't write unknown attribute `user_id`  

What does this mean?

StripeJS error: This customer has no attached payment source

Posted: 31 Oct 2016 05:19 AM PDT

This question has been asked before but there is no prominent solution on either of the links and the problem still persists after trying all the methods provided in the links. I am trying to generate a stripe subscription plan and each time I go through the process I get the error as "This customer has no attached payment source." As you can see in the screenshot that the stripe_card_token also gets generated and I have console.log the token also from JS and that also gets generated. I have attached all the relevant code files.

Github link for this project: https://github.com/arpit016/picture-app

Stripeerror screenshot

enter image description here

user.rb file

  class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable, :confirmable,           :recoverable, :rememberable, :trackable, :validatable      belongs_to :plan    attr_accessor :stripe_card_token      def save_with_payment      if valid?        customer = Stripe::Customer.create(          :source => stripe_card_token,          :email => email,          :plan => plan_id        )          self.stripe_customer_token = customer.id        save!      end    end    end  

users.js file

$(document).ready(function() {      Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));        $('#form-submit-btn').click(function(event) {          event.preventDefault();          $('input[type=submit]').prop('disabled', true);          var error = false;          if (!error) {              Stripe.card.createToken($('#new_user'), stripeResponseHandler);          }          return false;      }); //form submission        function stripeResponseHandler(status, response){          if (status == 200){              //Get a reference to the form              var f = $('#new_user');                //Get the token from the response              var token = response.id;              console.log("Token:" + token);                //Add the token to the form              f.append('<input type="hidden" name="user[stripe_card_token]" value="' + token + '" />');              console.log(f)                //Submit the form              f.get(0).submit();          }          else {              $('#stripe_error').text(response.error.message).show();              $('input[type=submit]').attr('disabled', false)          }      }  });  

Devise Modified Registrations controller

class Users::RegistrationsController < Devise::RegistrationsController     before_filter :select_plan, only: [:new]       def create        super do |resource|            if params[:plan]                resource.plan_id = params[:plan]                if resource.plan_id == 2                    resource.save_with_payment                else                    resource.save                end            end        end     end       def select_plan        unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2')          flash[:warning] = "Please select a valid membership"          redirect_to root_url        end     end      end  

Should my tests be creating db records for manditory associations?

Posted: 31 Oct 2016 05:02 AM PDT

This is a best-practices kind of question: If my Garden has a required field of user_id should my tests be actually creating the User in the database, or is there a better approach?

I'm finding that in my controller's update tests I'm running into cases where I want to reuse my garden factory, but the garden factory creates the required user in the database and I'm running into unique constraint violations on duplicate emails. So now I either need to make the factory generate unique emails or I need to learn how to mock up the associated record.

I guess the thing that really has me caught up short is that creating/updating a garden checks the database for the existence of the associated record. I don't yet understand how I could shortcut that. And I also don't know if that is necessary? If I set up the database_cleaner gem to perform tests as database transactions by default, perhaps I don't have to worry about how many User records are being "written"?

Rails + Ajax render multiple time during while loop

Posted: 31 Oct 2016 04:08 AM PDT

I have a form that is send asynchronously thanks to remote: true

Inside my controller I have a loop because it needs to execute some particular action multiple times.

Today I render only the result when the loop is finished and it's working but I would like to be able to render a progression each loop time, but when I use respond_to inside the loop there is an error

AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action.)

I also already tried with render_to_string but nothing shows up.

How can I bypass that to render a progression percentage (for example) of the loop to the view?


My controller

def run    while condition      # perform some actions      render_to_string :partial => "static_pages/message_sent", :locals => { :message_sent => "Some text<br />" }      respond_to do |format|        format.js{ render :partial => "static_pages/message_sent", :locals => { :message_sent => "Some text<br />" } }      end    end  end  

My view

<%= form_tag("/run", method: "post", remote: true) do %>    # Some form inputs    <%= submit_tag("Start", :id => "start_script", data: { disable_with: "Wait..." }) %>  <% end %>    <br /><br />    <h3>Result :</h3>  <div id="script_output"></div>  

Partial _message_sent.html.erb

$('#script_output').append("DOES IT SHOWS UP?"); # No it doesn't  

run.js.erb (working only when the loop ends)

$('#script_output').append("<%= @output.html_safe %>")  

How precompile css3 include attribute

Posted: 31 Oct 2016 05:03 AM PDT

I have a css:

.answer_meta_outer {    border-bottom: 1px dashed #ababab;     margin: 0 0 45px;     &:after {      @include clr;    }   }  

I got a error:

rake aborted!  Sass::SyntaxError: Undefined mixin 'clr'.  

File name is app/assets/stylesheets/responsive.css

Help me fix it please :)

Carrierwave - File not removed automatically when changing upload directory

Posted: 31 Oct 2016 03:53 AM PDT

I'm using Carrierwave for file upload in my Rails app.

I followed the How-To Secure Upload guide to secure my uploads. It works perfectly, but the uploaded file is not removed when it's owner (the model using the uploader) is destroyed. I get no error messages, the file is just left where it was uploaded.

I tried changing it back to upload files to public/uploads and files are removed as they should.

Lookup with dynamic parameter in Rails

Posted: 31 Oct 2016 04:37 AM PDT

In my Rails 5 application I need to be able to lookup data based on the type of the incoming params[:id] value that is being send from a 3rd party app. Each Model has two unique identifiers: id and cuid, and the received value can be either one of them. The problem is easily is illustrated like this:

if params[:id][/^\d+$/] # if it is numeric    @shipment = Shipment.find(params[:id])  elsif params[:id].present?    @shipment = Shipment.find_by_cuid(params[:id])  end  

In the routes I have to define what parameter to use for lookup, e.g.:

resources :shipments, param: :cuid  

But that ofc doesn't do the trick if I need to be able to lookup dynamically in both columns based on the data-type (and yes, I know that the incoming type will always be string by default).

Calling Google Drive API using Ruby on Rails Framework

Posted: 31 Oct 2016 03:19 AM PDT

I am trying to get this code to work which is mentioned as example on Google-auth-library-ruby

require 'googleauth'  require 'googleauth/web_user_authorizer'  require 'googleauth/stores/redis_token_store'  require 'redis'    client_id = Google::Auth::ClientId.from_file('/path/to/client_secrets.json')  scope = ['https://www.googleapis.com/auth/drive']  token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)  authorizer = Google::Auth::WebUserAuthorizer.new(    client_id, scope, token_store, '/oauth2callback')      get('/authorize') do      # NOTE: Assumes the user is already authenticated to the app      user_id = request.session['user_id']      credentials = authorizer.get_credentials(user_id, request)      if credential`enter code here`s.nil?          redirect authorizer.get_authorization_url(login_hint: user_id,         request: request)     end         # Credentials are valid, can call APIs         # ...  end    get('/oauth2callback') do      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(      request)      redirect target_url  end  

in the get '/authorize' method is always nil even the user is logged in and authenticated using Devise Gem and Google Oauth2 gem .

Can anyone may be share an example in rails framework how to obtain subsequent authorizations from Google to access any of their apis for which the user has given consent

Even the ruby methods used on the Google website seems to have been deprecated so not finding much information online

Thank you in advance

How to restrict upload image type in tinymce-rails?

Posted: 31 Oct 2016 05:16 AM PDT

I am using (Rails 5):

gem 'tinymce-rails', '>= 4.4.0'  gem 'tinymce-rails-imageupload', '~> 4.0.0.beta'  

I would like to somehow restrict the filetype of an uploaded image - as JPEG, PNG, GIF etc. Now the user can upload any filetype (even non-images) - with any extension.

How to do that correctly?

Rails 5: edit user roles in single view

Posted: 31 Oct 2016 05:06 AM PDT

I have view where current_user can select its users and edit their roles. I'm struggling to create single view (without loading edit path) where on user select from drop-down, particular role info is shown and can be edited.

In /controllers/common/roles_controller.rb I have this code, which in Index allows to find users and then I go to Edit:

def index    @users = User.joins(:accounts).where("accounts.company_id IN (?)", current_user.companies.pluck(:id)).distinct  end    def edit    @role = Role.find(params[:id])  end    private   def correct_role    redirect_to(errors_path) unless current_user.company_user_roles.where(id: params[:id]).exists?   end   def role_params    params.require(:role).permit(:general, :dashboard, ../different params/.., user_id)   end  

In /views/common/roles/index.html.erb I have this, however I'm not sure if this is the most effective and correct way:

<% @users.each do |user| %>     <% for role in user.roles %>  <option value="<%= role.id %>" data-edit-url="<%= edit_common_role_path(role.id) %>"><%= user.name %></option>  #Here below I have JS, which on user select go to particular user role edit  

which basically allows on user select go to particular role edit.

I can edit role with this /views/common/roles/edit.html.erb code:

<%= form_for([:common, @role]) do |f| %>    <%= f.select :general, Role.generals.to_a.map { |w| [w[0].humanize, w[0]] }, {}, {class:"form-control m-b"} %>    <%= f.select :dashboard, Role.dashboards.map { |w| [w[0].humanize, w[0]] }, {}, {class:"form-control m-b"} %>  

In /models/role.rb I have this:

class Role < ApplicationRecord  belongs_to :user, optional: true, inverse_of: :roles  accepts_nested_attributes_for :user  validates :user_id, presence: true    enum general: { seller: 1, buyer: 2, seller_buyer: 3}, _suffix: true  enum dashboard: { denied: 0, viewer: 1, editer: 2, creater: 3, deleter: 4}, _suffix: true  #More enum columns follow here...  

There are column user_id in roles table.

In /models/company.rb I have this:

class Company < ApplicationRecord  has_many :accounts, dependent: :destroy  has_many :users, through: :accounts  has_many :user_roles, through: :users, source: :roles  

In /models/account.rb I have this:

class Account < ApplicationRecord  belongs_to :company  belongs_to :user  accepts_nested_attributes_for :company, :user  end  

How to do I create single view where roles of particular user are loaded and then can be edited? Thank you for help or any hint!

Rails has_and_belongs_to_many on 2 level association

Posted: 31 Oct 2016 02:26 AM PDT

This is related to this previously asked question

I have a has_and_belongs_to_many in place between Product and Supplier.

In my view I use:

<td><%= product.suppliers.map {|supplier| supplier.NAME }.join(', ') %></td>  

To show list of suppliers comma separated on each row for each product in my table.

I now need to show the same list on invoices index view. Invoices table has a column PRODUCT. I have already set belongs_to :product on Invoice model.

I tried in my invoices index view:

<td><%= invoice.product.suppliers.map {|supplier| product.supplier.NAME }.join(', ') %></td>  

but it returns

error undefined local variable or method `product'

Why isn't that working? How can I fix it? Thanks in advance.

Layout for admins and users Login page

Posted: 31 Oct 2016 02:18 AM PDT

I have admin user authentication with devise I generated devise for user and one for admin and i am making layout using main devise layout page here is my route file

devise_for :admins    devise_scope :admin do    get '/admins/sign_out' => 'devise/sessions#destroy'    authenticated :admin do      root 'home#index'    end    #  delete "/logout" => "devise/sessions#destroy"  end    devise_for :users    devise_scope :user do    get '/users/sign_out' => 'devise/sessions#destroy'    authenticated :user do      root 'user_home#index', as: :authenticated_root    end      unauthenticated do      root 'devise/sessions#new', as: :unauthenticated_root    end  end  

I want to differentiate between the title of the admin page and the user page login.

Thanks a lot

Koala support for multiple FB Apps at the same time?

Posted: 31 Oct 2016 12:03 AM PDT

I'm initializing Koala with one FB App's info (app id, secret, callback url) and that is the usual one that I need to use for making graph api calls.

However, I need to occasionally make calls within the same RoR process to the FB graph api for a different FB App. What's the best way to do this for one-off calls that I need to make for the 2nd FB App? I thought initializing a new object like this would work, but it still seems to be using the original app info:

k = Koala::Facebook::API.new(user_fb_token, APP_2_SECRET)  

Ideally, it can support multiple apps at the same time so that I don't have to worry about other calls accidentally using the 2nd app if I re-initialize Koala.

How to paginate users with more than 0 object of attribute boolean: false?

Posted: 31 Oct 2016 12:49 AM PDT

How to paginate users with more than 0 publish challenges?

controller

Attempt 1

@users, @alphaParams = User    .select{ |user| user.challenges.publish > 0 }    .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}  

Attempt 2

@users, @alphaParams = User    .where(self.challenges.publish > 0)    .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}  

Attempt 3

@users, @alphaParams = User.joins(:challenges)    .where('challenges.publish > 0')    .distinct    .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}  

model

scope :publish, ->{ where(conceal: false) }  

How to show forgot error messages in a modal with devise functionality?

Posted: 31 Oct 2016 12:07 AM PDT

I am having a login form where there is a forgot password link and when we click on that a Modal pop-up appears where we enter our email address. This is fine when we enter the correct / existing email but if we enter any wrong email or the email doesn't exist in database, it is not showing any error message. Please help.

I tried using <%= devise_error_messages! %> but no use. I think we have to use jQuery / javascript functionality inorder to show error. But how to show on the model itself? This is my view:

<div class="container">    <div class="section section-signup">          <%= semantic_form_for(@resource, :as => resource_name, :url => user_session_path, :remote => true, :format => :json, :html => { :id => 'mainLogin' }) do |f| %>          <%= f.inputs do %>          <%= f.input :email, :label => 'Your email address', :input_html => { :placeholder => "Email"} %>                  <%= f.input :password, :label => 'Your password', :input_html => { :placeholder => "Password"} %>              <% end %>          <%= f.buttons do %>            <% if devise_mapping.rememberable? %>              <%= f.input :remember_me, :as => :boolean, :label => "Remember me on this computer", :required => false,  :input_html => {:class => "remember-me"} %>            <% end %>          <%= f.commit_button :label => 'Sign me in', :button_html => {:class => 'login submit button', :disable_with => 'Wait...', :id => 'user_submit' }%>            <% end %>        <div class="forgot">Yikes: <a class="pass-reset-btn cboxElement" href="#pass-reset" data-toggle="modal" data-target="#myModal">I forgot my password!</a></div>          <% end %>    </div>  </div>    <!-- Modal -->  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">    <div class="modal-dialog">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>          <h4 class="modal-title" id="myModalLabel">Password reset</h4>        </div>        <div class="modal-body">          <p>Enter your email address and we'll shoot you a link for resetting your password.</p>          <!-- Start Fromtastic Markup -->          <%= semantic_form_for(resource_name, :url => password_path(resource_name), :remote => true, :format => :json, :html => { :id => 'password_reset' }) do |f| %>            <%= f.inputs do %>              <%= f.input :email, :label => 'Your email address', :input_html => { :placeholder => "Enter your email..."}%>            <% end %>            <%= f.buttons do %>              <%= f.commit_button :label => 'Send me that link', :button_html => {:class => 'submit button', :disable_with => 'Wait...' }%>            <% end %>            <div class="clearfix"></div>          <% end %>          <!-- End Fromtastic Markup -->        </div>      </div>    </div>  </div>  

Sunday, October 30, 2016

Jquery datepickers date issue | Fixed issues

Jquery datepickers date issue | Fixed issues


Jquery datepickers date issue

Posted: 30 Oct 2016 07:53 AM PDT

I have a rails application where I am using jquery datepicker with 2 input fields like this.

<input type="text" class="form-control datePicker" placeholder="Check In" id="dpd1" value="<%= (Date.today).strftime('%d-%m-%Y').to_s %>" name="arrival_date_disp">    <input type="text" class="form-control datePicker" placeholder="Check Out" id="dpd2" value="<%= (Date.today + 1).strftime('%d-%m-%Y').to_s %>" name="departure_date_disp">  

Jquery code is like this -

  $("#dpd1").datepicker({      minDate : new Date,      yearRange: "-90:+1",      changeMonth: true,      changeYear: true,      altField  : '#arrival_date',      altFormat : 'yy-mm-dd',      dateFormat : 'dd-mm-yy',      numberOfMonths: 2    });         $("#dpd2").datepicker({      minDate : $("#dpd1").datepicker( "getDate" ),      yearRange: "-90:+1",      changeMonth: true,      changeYear: true,      altField  : '#departure_date',      altFormat : 'yy-mm-dd',      dateFormat : 'dd-mm-yy',      numberOfMonths: 2,      setDate: "31-10-2016"    });  

The problem is there is only one datepicker instance being initialized for both fields and as such when I click open the datepicker it shows same date for both of them (obvious as same datepicker is being used).

How do I show different date for second field ?

first one

second one

Rails global variables are not updating on update

Posted: 30 Oct 2016 07:51 AM PDT

I have an $template variable defined in application_controller.rb which contains some site template code changed thought admin

The problem is when I save or update it, it doesn't affect site till server restart, which is really uncomfortable in production

$template = Template.first  .....    $template.header.html_safe  

In logs I can the that $template variable make and SQL and the very beginning (before Puma booted) and probably that's the way how global vars should be working.

P.S. Im using active_admin and update from there

Embed Shiny app in Rails site

Posted: 30 Oct 2016 07:16 AM PDT

I am trying to create an interactive chart using Shiny, but I cannot find any direction about how to embed the shiny app in a ruby on rails site. Can anyone provide a simple example of how to do this?

Rails eager_load with conditions on association

Posted: 30 Oct 2016 07:09 AM PDT

I have a Rails application which has Stations (weather stations) and Observations. The app shows many weather stations on a map with the current wind speed and direction.

I have a method which is used on the stations#index method which selects the stations and joins the latest observation per station.

class Station < ActiveRecord::Base    has_many :observations    def self.with_observations(limit = 1)      eager_load(:observations).where(        observations: { id: Observation.pluck_from_each_station(limit) }      )    end  end  

Observation.pluck_from_each_station returns an array of ids. The observations table contains many thousands of rows so this is necessary to keep rails from eager loading thousands of records.

This method should return all the stations - whether the have any observations or not. However this is currently not the case.

it "includes stations that have no observations" do    new_station = create(:station)    stations = Station.with_observations(2)    expect(stations).to include new_station # fails  end  

From my understanding a LEFT OUTER JOIN should return all rows wether the there are any results in the joined table or not. Why is this not working as expected?

This is an example of the SQL generated:

SELECT "stations"."id" AS t0_r0,         "stations"."name" AS t0_r1,         "stations"."hw_id" AS t0_r2,         "stations"."latitude" AS t0_r3,         "stations"."longitude" AS t0_r4,         "stations"."balance" AS t0_r5,         "stations"."timezone" AS t0_r6,         "stations"."user_id" AS t0_r7,         "stations"."created_at" AS t0_r8,         "stations"."updated_at" AS t0_r9,         "stations"."slug" AS t0_r10,         "stations"."speed_calibration" AS t0_r11,         "stations"."firmware_version" AS t0_r12,         "stations"."gsm_software" AS t0_r13,         "stations"."description" AS t0_r14,         "stations"."sampling_rate" AS t0_r15,         "stations"."status" AS t0_r16,         "observations"."id" AS t1_r0,         "observations"."station_id" AS t1_r1,         "observations"."speed" AS t1_r2,         "observations"."direction" AS t1_r3,         "observations"."max_wind_speed" AS t1_r4,         "observations"."min_wind_speed" AS t1_r5,         "observations"."temperature" AS t1_r6,         "observations"."created_at" AS t1_r7,         "observations"."updated_at" AS t1_r8,         "observations"."speed_calibration" AS t1_r9  FROM   "stations"         LEFT OUTER JOIN         "observations"         ON "observations"."station_id" = "stations"."id"  WHERE  "observations"."id" IN (450, 500, 550, 600, 650, 700, 750, 800);  

Ruby on Rails building a pivot table

Posted: 30 Oct 2016 06:34 AM PDT

I have a database table stockdiaries. With columns: ID, PRODUCT, UNITS, REASON

Sample values:

1,Apple,5,purchase

2,Orange, 8,purchase

3,Apple,-3,sale

4,Orange,-5,sale

Then this joins products table from where I get product.NAME, product.CATEGORY and so on.

In my view I want to display a table with columns: PRODUCT, SOLD, PURCHASED, STOCK And values:

Apple,3,5,2

Orange,5,8,3

SOLD is the sum of units sold, PURCHASED the sum of units purchased.

I really don't know what is the best approach in the first place. But is it possible to use in my view something like:

<%= stockdiary.product.NAME %>  <%= stockdiary.sold %>  <%= stockdiary.purchased %>  <%= stockdiary.stock %>  

to show the columns I want?

In other words is there a way I can define purchased in my model or controller to calculate sum(UNITS) where REASON=purchase?

If yes what is the syntax to use?

If no what approach should I follow then?

Ruby on Rails - showing all instances in a view, with specific column value, returned by other table column

Posted: 30 Oct 2016 06:10 AM PDT

First, my schema looks like this:

create_table "categories", force: :cascade do |t|  t.text     "name"  t.text     "slug"  end    create_table "fields", force: :cascade do |t|  t.integer  "order"  t.string   "title"  t.text     "tipo"  t.text     "values"  t.integer  "sub_category_id"  end  add_index "fields", ["sub_category_id"], name: "index_fields_on_sub_category_id"    create_table "sub_categories", force: :cascade do |t|  t.integer  "category_id"  t.text     "name"  t.text     "slug"  end  add_index "sub_categories", ["category_id"], name: "index_sub_categories_on_category_id"  

This is my schema, a category has many sub_categories, and a sub_category has many fields. Im trying to generate a view which contains all fields of a specific sub_category, i've already passed the sub_category.id to this view, but thats all i could do.

Its not that difficult i imagine, but im a begginer on rails. How can i do it? The routes are also a problem, since i have to create a new controller function. But the route generated by my application already looks like this: "/sub_categories/mysubcategory56/visualizeform?sub_category=56"

Creating multiple object in rails

Posted: 30 Oct 2016 06:01 AM PDT

I want to make in one form calendar and multiple visits for this calendar (like 10,100,1000) How can i achieve this? How to make multiple objects for calendar in controller?

Rails throws 'load_missing_constant: expected path_to_x to define X', yet it does

Posted: 30 Oct 2016 05:13 AM PDT

My error:

/Users/-/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:512:in `load_missing_constant':   Unable to autoload constant Types::QueryType, expected /Users/-/project/app/graph/types/query_type.rb to define it (LoadError)  

app/graph/schema.rb:

module Graph    Schema = GraphQL::Schema.define do      query Types::QueryType    end  end  

app/graph/types/query_type.rb:

module Graph    module Types      QueryType = GraphQL::ObjectType.define do        name 'Query'      end    end  end  

config/application.rb:

config.autoload_paths << "#{Rails.root}/app/graph"  config.autoload_paths << "#{Rails.root}/app/graph/interfaces"  config.autoload_paths << "#{Rails.root}/app/graph/types"  config.autoload_paths << "#{Rails.root}/app/graph/unions"  

Rails correctly expects Types::QueryType to be defined in app/graph/types/query_type.rb, however - weirdly enough - somehow concludes that file does not define Types::QueryType, which it clearly does.

Even weirder: when jumping into a console, it only throws this error the first time Types::QueryType is requested. The second time however Types::QueryType resolves to the correct definition.

I'm probably doing something wrong here, but I just can't seem to find it.

compared with non class/module in controller

Posted: 30 Oct 2016 04:56 AM PDT

How to only include users who have more than 0 challenges.publish?

class UsersController < ApplicationController    def index      @users, @alphaParams = User.select{ |user| user.challenges.publish > 0}.alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}    end  end  

Maybe I should use where instead of select?

Rails has_and_belongs_to_many how to change default iforeign key and show list of results on csv

Posted: 30 Oct 2016 05:56 AM PDT

I have tables products and suppliers. And a joining table products_sup.

I have in my model Product:

has_and_belongs_to_many :suppliers, :join_table => "products_sup"  

And in my model Supplier:

has_and_belongs_to_many :products, :join_table => "products_sup"  

In my view I would like to display list of suppliers for each product.

But it returns

Mysql2::Error: Unknown column 'products_sup.product_id' in 'on clause':

Note that NAME is a column in suppliers db table. And products_sup is the joining table.

The problem is that products_sup contains columns PRODUCT, SUPPLIER. While rails by default is looking for supplier_id and product_id. But I can't find the right syntax to change these default columns. The same way that for a belongs_to I would use `:foreign_key => 'custom_foreign_key_column'

What should I use in my view and models to achieve it?

Cannot select element with jQuery rails

Posted: 30 Oct 2016 04:03 AM PDT

I'm migrating a project from Middleman to Rails5 and I have a problem with jQuery. I cannot select a form with jQuery, instead of returning a DOM element it returned a jQuery object. Here's a screenshot of what I mean:

enter image description here

I'm sorry if this is a stupid question but I've been googling for 1 hour and feel pretty desperate right now. I also included jQuery in the manifest file so I cannot think of anything that's wrong with it.

Add Rails minitest fixtures for a single test

Posted: 30 Oct 2016 03:19 AM PDT

Is there a way to a Rails minitest fixtures just for one specific test or set of tests? I ask because I want to display Delayed::Job jobs using the standard index/show/delete schemes so I want to fake some Delayed::Job objects to test my views. But I don't want these objects present when I actually test my Delayed::Job processing code so I'd like to add then just for once specific set of tests.

Rails: use REJECT_IF dependent on parent record and for specific action for nested attributes

Posted: 30 Oct 2016 03:19 AM PDT

In my app I am building to learn Rails and Ruby (am beginner), I have a polymorphic model between tag and annotation / document. These are implemented using nested fields and I need to validate the tag-fields using reject_if.


models set up using

belongs_to :tagable, :polymorphic => true  has_many :tags, :as => :tagable, dependent: :destroy  accepts_nested_attributes_for :tags, allow_destroy: true  

For tags related to annotations, this need to be the validations:

validates :content,             presence: true  validates :tagtype,             presence: true  validates :key,                 on: :update, presence: true, if: 'key_position.blank?' && 'key_regex.blank?'  validates :key_position,        on: :update, presence: true, if: 'key.blank?' && 'key_regex.blank?', format: { with: /(^(-?\d+,\s){3}-?\d+$){1}/, message: 'numeric and as x1, y1, x2, y2'}  validates :key_regex,           on: :update, presence: true, if: 'key_position.blank?'  validates :value_position,      on: :update, presence: true, if: 'value_regex.blank?', format: { with: /(^(-?\d+,\s){3}-?\d+$){1}/, message: 'numeric and as x1, y1, x2, y2'}  validates :value_regex,         on: :update, presence: true, if: 'value_position.blank?'  validate  :valid_key_regex,     on: :update  validate  :valid_value_regex,   on: :update  

def valid_key_regex    @valid_key_regex ||= Regexp.new(self.key_regex)    rescue => exception    errors.add(:key_regex, exception)  end    def valid_value_regex    @valid_value_regex ||= Regexp.new(self.value_regex)    rescue => exception    errors.add(:value_regex, exception)  end  

For tags related to documents, this need to be the validations:

validates :content,             presence: true  validates :tagtype,             presence: true  

I can make two methods for the reject_if of annotations and documents respectively, my questions now are:

  1. how can I check the action (on: :create, on: update...) for the separate attributes?
  2. how do I get specific error messages back to the user when saving the changes (I use simple_form)? (i.e. not reject silently?)
  3. how could I DRY the 2 separate methods in to one (if useful?)? Where to place it and how to check the related parent?

all advice, tips, examples welcome!

Nested loops using Cocoon Gem in Rails

Posted: 30 Oct 2016 03:18 AM PDT

So I'm building a recipe app where is user can create his own dish.

the problem im facing is in cocoon gem i have followed every step on their documentation but while creating the recipe the user is not able to see the nested form for ingredients. the form to fill in the ingredients just does not display. The main form works fine which has image, name and description. it saves displays perfectly. I'm trying to give all the chunks of code that I feel could have problem and could help you simulate my app. Thanks for the Help

code for the simple_form under file name --> _form.html.erb

<div id="panel-body">  <%= f.input :image, input_html: {class: "form-control"} %>  <%= f.input :name, input_html: {class: "form-control"} %>  <%= f.input :description, input_html: {class: "form-control"} %>    <div class="row">      <div class="col-md-6">      <h3>Ingredients</h3>      <div id="Ingredients">        <%= f.simple_fields_for :ingredients do |ingredient| %>          <%= render "ingredient_fields", f: ingredient %>        <% end %>        <div class="links">          <%= link_to_add_association 'Add', f, :ingredients, class: "btn btn-default add-button" %>        </div>      </div>    </div>  

code for the ingredient_fields under the file name --> _ingredient_fields.html.erb

<div class="form-inline clearfix">    <div class="nested-fields">      <%= f.input :name, input_html: {class: "form-input form-control"} %>      <%= link_to_remove_association "Remove", f, class: "btn btn-default form-button"%>    </div>  </div>  

code for the Recipe model

class Car < ApplicationRecord    has_many :ingredients      has_attached_file :image, styles: { medium: "450x250#" }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/      accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true      validates :name, :description, :image, presence: true  end  

code for Recipe controller

def recipe_params      params.require(:recipe).permit(:name, :description, :image, ingredient_attributes: [:id, :type, :displacment, :power, :torque, :layout, :_destroy])  

aws-sdk 2.3.0 and Paperclip 5.0.0 bad region

Posted: 30 Oct 2016 05:47 AM PDT

Im using the AWS-SDK 2.3.0 gem with paperclip 5.0.0 gem.

In my config/environment/development.rb file i have

config.paperclip_defaults = {      storage: :s3,      s3_region: 'eu-west-1',      s3_credentials: {        bucket: 'myBucketName',        access_key_id: 'xxxxxxxxxxxxxxxxxxxxxx',        secret_access_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'        }      }  

My bucket region in set as Ireland when I created my bucket so according to the document provided by AWS i set my s3 region as eu-west-1.

Im assuming my details are all correct but, when i upload an image, its gets saved to the bucket but it won't show on my rails app. If i right click on open image in new tab i get this error:

<Message>  The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.  </Message>  

Rails add link to edit attribute from another model

Posted: 30 Oct 2016 02:59 AM PDT

If I have a model Product and a model Category.

I have a table in products index showing products with columns like:

 <td><%= product.ID %></td>   <td><%= product.NAME %></td>   <td><%= product.category.NAME %></td>  

It shows values like:

1,salad, vegetable

2,apple,fruit

I want to be able to click on vegetable or fruit to edit them.

I tried:

<td><%= link_to product.category.NAME, [:edit, product.category] %>  

This takes me to a page

categories/1/edit

which returns

Couldn't find Product with 'ID'=

Instead it should go to

categories/edit/1

In my routes I have:

 match ':controller(/:action(/:ID))', :via => [:get, :post]   resources :categories  

What is the correct syntax to use in this case?

Is there a way to namespace a PORO class without a module

Posted: 30 Oct 2016 01:31 AM PDT

Here is my press_post/updater.rb file

class PressPost::Updater    def say_something      p 'hello world'    end  end  

But when I run things I get this ': uninitialized constant PressPost (NameError)

I know that other answers have touched around this.. One went so far as to make an empty module inside the class file on the first line.. That seems flawed.

I know there is a way to not have to do this extra code. I believe it's a config or something, but I don't know how to accomplish this.

Note.. I want to do this because these are in a sub directory and it is a whole lot easier searching the code for PressPost::Updater than Updater

How to trigger conditional if every date attribute is nil for current month of this year?

Posted: 30 Oct 2016 01:24 AM PDT

How to trigger conditional with @future_challenges if deadline is not equal to Date.current.year.month?

controller

@future_challenges = current_user.challenges.unaccomplished.order("deadline ASC").select{ |challenge| challenge.deadline > Date.current if challenge.deadline.present? }  

view

<% if @future_challenges != Date.current.year.month %> # Is giving true even if there are challenges with deadline in current month of this year    <div style="margin-top: -4px;"></div>  <% end %>  

Undefined method "has_attached_file" for my ActiveRecord model

Posted: 30 Oct 2016 12:17 AM PDT

I followed the docs at https://github.com/thoughtbot/paperclip exactly to install implement paperclip in my app for image uploading. I am currently using gem 'paperclip', '~> 5.0.0.beta1'. After I did the migration, the four columns were added onto my schema properly:

t.string   "picture_file_name"  t.string   "picture_content_type"  t.integer  "picture_file_size"  t.datetime "picture_updated_at"  

My paperclip should therefore be installed correctly. However, when I proceeded to add the following two lines onto my model class:

  has_attached_file :picture, styles: { medium: "300*300>", thumb: "100*100" }, default_url: "/images/start_project3.jpg"    validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/  

Everything broke. I try to create, search, or anything related to the model class in rails console, it yells at me with the following error:

NoMethodError: undefined method `has_attached_file' for #<Class:0x0055bd71ec0228>  

I have tried multiple versions of paperclip, from the earlier version 4.3.0 to the latest version of paperclip, but the problem persists. I also restarted my server in between changes and migrations, but that did not fix the problem. This is the migration that I performed:

class AddAttachmentPictureToProjects < ActiveRecord::Migration    def self.up      change_table :projects do |t|        t.attachment :picture      end    end      def self.down      remove_attachment :projects, :picture    end  end  

I am totally lost right now as to what to do. This is my gem file:

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.7.1'  # Use postgresql as the database for Active Record  gem 'pg', '~> 0.15'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  gem 'bcrypt', '~> 3.1.7'  gem 'pry-rails'  gem 'annotate'  # Use Unicorn as the app server  # gem 'unicorn'  gem 'faker'  # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development  gem 'pg_search'  gem 'paperclip', '~> 5.0.0.beta1'  # gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"  # gem "paperclip", "~> 4.3"    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'    gem 'faker'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end    group :production do    gem 'newrelic_rpm'    gem 'rails_12factor' # error feedback  end  

Postgres: Column updated but not detected.

Posted: 29 Oct 2016 11:59 PM PDT

So i initially had a foreign id tutor_id as type string. So i ran the following migrations.

change_column(:profiles, :tutor_id, 'integer USING CAST(tutor_id AS integer)')

The problem is that there was data already created which initially contained the tutor_id as type string. I did read however that by using CAST, the data should be converted into an integer.

So just to confirm i went into heroku run rails console to check the tutor_id of the profiles and tutor_id.is_a? Integer returns true.

However i am currently getting this error

ActionView::Template::Error (PG::UndefinedFunction: ERROR: operator does not exist: integer = text at character 66

Why is that so? Is the only way out to delete the data and to recreate it?

(I'm assuming the information provided above is enough to draw a conclusion, else i will add the relevant information too.)

Why is Capybara still passing when I delete JS file?

Posted: 29 Oct 2016 10:15 PM PDT

I have a small Rails app which Capybara, Rspec and Webkit for testing. It's a CRUD app to create items. I added a feature when user can input the id, then it will show the status of the item is shippable or not. When user enter the id, the app will make a Ajax call to item_path(id), then it will return the status of the item which will append to the view. I wrote test to check if the feature is and it's all passed. I did use bye bug to check the if the status get appended to the view, and I do see it. Then I accidentally DELETE the JavaScript file (items.js in assets). I run the test, all the tests are still passed; I did use byebug to check and I still see the status appended to view even though js file is deleted. Do you why test still pass? Thanks

How to create video viewing site using youtube API and Vimeo API on Ruby on rails

Posted: 29 Oct 2016 08:55 PM PDT

I want to create video viewing site using youtube API and Vimeo API on Ruby on rails.

But I cannot find useful information.

If you know about that in any website or book, let me know please.

Thanks

In Rails, how would I show a 'Goodbye' page that is *only* accessible immediately after the user signs out?

Posted: 29 Oct 2016 10:28 PM PDT

I was recently using Svbtle.com where they show a page immediately after logging out. It says "Goodbye.", along with link to go "Back to SVBTL".

I like the idea of a 'farewell' page, similar to how they did it, and would like to do something similar in a project I'm working on.

The 'farewell' page on Svbtle has a path of https://svbtle.com/notify?logout. When you reload the page or try to navigate to https://svbtle.com/notify?logout, it redirects you to the site landing page.

What is this magic?

How would I go about only showing a page upon user logout, but then prevent them from visiting it otherwise?

I'm using Rails 5.0.0.1 and Devise for authentication.

Display specific user info in app

Posted: 29 Oct 2016 09:02 PM PDT

I'm trying to manipulate user data within my iOS app. I'm using a rails backend and AWS. I have a working user login view where a user inputs their name, email, and password. I'm trying to display a user's name on their post, for example, Created by: Lexie (where 'Lexie' is pulled from the DB). I'm more familiar with user creation in rails, and am looking for a similar action to User.name, User.first_name, etc. Still trying to learn the basics of this process in Swift. Any idea how to pull and display the data by string interpolation in another view? Thanks so much for the help :)!

Here is my viewController code:

//  //  ViewController.swift  //      import UIKit    class ViewController: UIViewController {        @IBOutlet weak var signinBackgroundView: UIView!      @IBOutlet weak var signupBackgroundView: UIView!      @IBOutlet weak var signinEmailTextField: UITextField!      @IBOutlet weak var signinPasswordTextField: UITextField!      @IBOutlet weak var signupNameTextField: UITextField!      @IBOutlet weak var signupEmailTextField: UITextField!      @IBOutlet weak var signupPasswordTextField: UITextField!      @IBOutlet weak var activityIndicatorView: UIView!      @IBOutlet weak var passwordRevealBtn: UIButton!        let httpHelper = HTTPHelper()        override func viewDidLoad() {          super.viewDidLoad()          // Do any additional setup after loading the view, typically from a nib.            self.activityIndicatorView.layer.cornerRadius = 10      }        override func didReceiveMemoryWarning() {          super.didReceiveMemoryWarning()          // Dispose of any resources that can be recreated.      }        @IBAction func passwordRevealBtnTapped(sender: AnyObject) {          self.passwordRevealBtn.selected = !self.passwordRevealBtn.selected            if self.passwordRevealBtn.selected {              self.signupPasswordTextField.secureTextEntry = false          } else {              self.signupPasswordTextField.secureTextEntry = true          }      }        func displaSigninView () {          self.signinEmailTextField.text = nil          self.signinPasswordTextField.text = nil            if self.signupNameTextField.isFirstResponder() {              self.signupNameTextField.resignFirstResponder()          }            if self.signupEmailTextField.isFirstResponder() {              self.signupEmailTextField.resignFirstResponder()          }            if self.signupPasswordTextField.isFirstResponder() {              self.signupPasswordTextField.resignFirstResponder()          }            if self.signinBackgroundView.frame.origin.x != 0 {              UIView.animateWithDuration(0.8, animations: { () -> Void in                      self.signupBackgroundView.frame = CGRectMake(320, 134, 320, 284)                      self.signinBackgroundView.alpha = 0.3                        self.signinBackgroundView.frame = CGRectMake(0, -40, 320, 284)                      self.signinBackgroundView.alpha = 1.0                  }, completion: nil)          }      }        func displaySignupView () {          self.signupNameTextField.text = nil          self.signupEmailTextField.text = nil          self.signupPasswordTextField.text = nil            if self.signinEmailTextField.isFirstResponder() {              self.signinEmailTextField.resignFirstResponder()          }            if self.signinPasswordTextField.isFirstResponder() {              self.signinPasswordTextField.resignFirstResponder()          }            if self.signupBackgroundView.frame.origin.x != 0 {              UIView.animateWithDuration(0.8, animations: { () -> Void in                      self.signinBackgroundView.frame = CGRectMake(-320, 134, 320, 284)                      self.signinBackgroundView.alpha = 0.3;                        self.signupBackgroundView.frame = CGRectMake(0, 134, 320, 284)                      self.signupBackgroundView.alpha = 1.0                    }, completion: nil)          }      }        func displayAlertMessage(alertTitle:String, alertDescription:String) -> Void {          // hide activityIndicator view and display alert message          self.activityIndicatorView.hidden = true          let errorAlert = UIAlertView(title:alertTitle, message:alertDescription, delegate:nil, cancelButtonTitle:"OK")          errorAlert.show()      }        @IBAction func createAccountBtnTapped(sender: AnyObject) {          self.displaySignupView()      }        @IBAction func cancelBtnTapped(sender: AnyObject) {          self.displaSigninView()      }          @IBAction func signupBtnTapped(sender: AnyObject) {          // Code to hide the keyboards for text fields          if self.signupNameTextField.isFirstResponder() {              self.signupNameTextField.resignFirstResponder()          }            if self.signupEmailTextField.isFirstResponder() {              self.signupEmailTextField.resignFirstResponder()          }            if self.signupPasswordTextField.isFirstResponder() {              self.signupPasswordTextField.resignFirstResponder()          }            // start activity indicator          self.activityIndicatorView.hidden = false            // validate presence of all required parameters          if self.signupNameTextField.text != "" && self.signupEmailTextField.text != "" && self.signupPasswordTextField.text != "" {              makeSignUpRequest(self.signupNameTextField.text!, userEmail: self.signupEmailTextField.text!, userPassword: self.signupPasswordTextField.text!)          } else {              self.displayAlertMessage("Parameters Required", alertDescription: "Some of the required parameters are missing")          }      }            @IBAction func signinBtnTapped(sender: AnyObject) {          // resign the keyboard for text fields          if self.signinEmailTextField.isFirstResponder() {              self.signinEmailTextField.resignFirstResponder()          }            if self.signinPasswordTextField.isFirstResponder() {              self.signinPasswordTextField.resignFirstResponder()          }            // display activity indicator          self.activityIndicatorView.hidden = false            // validate presense of required parameters          if self.signinEmailTextField.text != "" &&              self.signinPasswordTextField.text != "" {              makeSignInRequest(self.signinEmailTextField.text!, userPassword: self.signinPasswordTextField.text!)          } else {              self.displayAlertMessage("Parameters Required",                                       alertDescription: "Some of the required parameters are missing")          }      }        func updateUserLoggedInFlag() {          // Update the NSUserDefaults flag          let defaults = NSUserDefaults.standardUserDefaults()          defaults.setObject("loggedIn", forKey: "userLoggedIn")          defaults.synchronize()      }        func saveApiTokenInKeychain(tokenDict:NSDictionary) {          // Store API AuthToken and AuthToken expiry date in KeyChain          tokenDict.enumerateKeysAndObjectsUsingBlock({ (dictKey, dictObj, stopBool) -> Void in              let myKey = dictKey as! String              let myObj = dictObj as! String                if myKey == "api_authtoken" {                  KeychainAccess.setPassword(myObj, account: "Auth_Token", service: "KeyChainService")              }                if myKey == "authtoken_expiry" {                  KeychainAccess.setPassword(myObj, account: "Auth_Token_Expiry", service: "KeyChainService")              }          })            self.dismissViewControllerAnimated(true, completion: nil)      }          func makeSignUpRequest(userName:String, userEmail:String, userPassword:String) {          // 1. Create HTTP request and set request header          let httpRequest = httpHelper.buildRequest("signup", method: "POST",              authType: HTTPRequestAuthType.HTTPBasicAuth)            // 2. Password is encrypted with the API key          let encrypted_password = AESCrypt.encrypt(userPassword, password: HTTPHelper.API_AUTH_PASSWORD)            // 3. Send the request Body          httpRequest.HTTPBody = "{\"full_name\":\"\(userName)\",\"email\":\"\(userEmail)\",\"password\":\"\(encrypted_password)\"}".dataUsingEncoding(NSUTF8StringEncoding)            // 4. Send the request          httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in              if error != nil {                  let errorMessage = self.httpHelper.getErrorMessage(error)                  self.displayAlertMessage("Error", alertDescription: errorMessage as String)                    return              }                self.displaSigninView()              self.displayAlertMessage("Success", alertDescription: "Account has been created")          })      }        func makeSignInRequest(userEmail:String, userPassword:String) {          // Create HTTP request and set request Body          let httpRequest = httpHelper.buildRequest("signin", method: "POST",                                                    authType: HTTPRequestAuthType.HTTPBasicAuth)          let encrypted_password = AESCrypt.encrypt(userPassword, password: HTTPHelper.API_AUTH_PASSWORD)            httpRequest.HTTPBody = "{\"email\":\"\(self.signinEmailTextField.text!)\",\"password\":\"\(encrypted_password)\"}".dataUsingEncoding(NSUTF8StringEncoding);            httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in              // Display error              if error != nil {                  let errorMessage = self.httpHelper.getErrorMessage(error)                  self.displayAlertMessage("Error", alertDescription: errorMessage as String)                    return              }                // hide activity indicator and update userLoggedInFlag              self.activityIndicatorView.hidden = true              self.updateUserLoggedInFlag()                do {                    let responseDict = try NSJSONSerialization.JSONObjectWithData(data,                      options: NSJSONReadingOptions.AllowFragments) as! NSDictionary                  //var stopBool : Bool                    // save API AuthToken and ExpiryDate in Keychain                  self.saveApiTokenInKeychain(responseDict)              }              catch let error as NSError {                  print(error.localizedDescription)              }              })      }  }  

Creating a login macro for feature specs - Rails

Posted: 29 Oct 2016 07:55 PM PDT

I've seen apps use a macro before for creating logins for feature tests. I'm in the process of building out the configuration for my test suite and this is the final task I was hoping to accomplish. Basically I want to write this line in my tests

login(user)  

Instead of what I'm doing right now.

create(:user)  visit "/"    click_link "Sign In"  expect(current_path).to eql(user_session_path)    fill_in "user_email", with: "robert@example.com"  fill_in "user_password", with: "password"  click_button "Log in"  

If anybody know what I need that would be great! Thank you.

Query table without returning ActiveRecord_Relation

Posted: 29 Oct 2016 07:43 PM PDT

Basically I have an app that have a Projects table, and a project belongs to a Client (and the client has a column in the table for it's location).

I've created a search feature where the idea is you search for the project by location then client. I was hoping to use JavaScript to filter out any clients that weren't from the selected locations. I followed a tutorial to do this, however the tutorial assumed that the client belonged to a location, and therefore I'm the below code doesn't seem to work. Is there a way to basically say 'If Client.location = one of the selected locations, show it'

clients = $('#search_client').html()  $('#search_location').change ->      location = $('#search_location :selected').map(() ->          return $(this).text();      ).get().join().split(',');      console.log(location)      options_array = []      for l in location          options_array.push $(clients).filter('optgroup[label="'+l+'"]').html()      if options_array          $('#search_client').html(options_array.join(''))      else          $('#search_client').empty()  

Rails migration to change column type from text to json (Postgresql)

Posted: 29 Oct 2016 07:16 PM PDT

I've been trying unsuccessfully to change a column type in my Postgres database from text to json. Here's what I've tried...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0]    def up      execute 'ALTER TABLE places ALTER COLUMN notes TYPE json USING (notes::json)'    end      def down      execute 'ALTER TABLE places ALTER COLUMN notes TYPE text USING (notes::text)'    end  end  

Also...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0]    def up      change_column :places, :notes, 'json USING CAST(notes AS json)'    end      def down      change_column :places, :notes, 'text USING CAST(notes AS text)'    end  end  

Both of these return the same error...

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type json  

Making dates go back passed 2011 DateTime Generator on Ruby on Rails Scaffold

Posted: 30 Oct 2016 08:11 AM PDT

I am making a new site and I cannot get dates in a generated scaffold to go back passed 2011. The months , days, and time work perfectly. However, I cannot moved the year past back 2001. I am making an Astrology Porn site with a database of compatible female pornstars with an inputted zodiac sign. I hope you can help me fix the date issues I am trying to add Kianna Dior to the zodiac sign and she was born in 1969, so it will not work with rails 5 default generator for any dateTime columns that are generated via scaffold.

How do I convert this to a UJS request?

Posted: 29 Oct 2016 05:35 PM PDT

I have a Profile and that has_many :ratings.

I have a set of JS controls that control the input of that rating on the profile looks like this:

enter image description here

What I want to happen is whenever the controls are moved, it automagically updates the rating on that profile the background -- via UJS (or w/e is best per Rails 5).

This is in my Profile#Show view:

<div class="col-md-3">    <div class="profile-data">      <table class="table table-condensed">          <tbody>          <tr>              <td>                  <p>                    <button type="button" class="btn btn-danger m-r-sm slider-step-value" id="slider-step-value-speed">5</button>                    Speed                  </p>                  <div class="slider"></div>              </td>              <td>                  <p>                    <button type="button" class="btn btn-primary m-r-sm slider-step-value" id="slider-step-value-tackling">3</button>                    Tackling                  </p>                  <div class="slider"></div>              </td>          </tr>          <tr>              <td>                  <p>                    <button type="button" class="btn btn-success m-r-sm slider-step-value" id="slider-step-value-dribbling">9</button>                    Dribbling                  </p>                  <div class="slider"></div>              </td>              <td>                  <p>                    <button type="button" class="btn btn-danger m-r-sm slider-step-value" id="slider-step-value-passing">7</button>                    Passing                  </p>                  <div class="slider"></div>              </td>          </tr>          </tbody>      </table>    </div>  </div>  

This is my profiles.js:

$(document).on('turbolinks:load', function() {    var sliders = $('.slider');    var buttons = $('.slider-step-value');      for ( var i = 0; i < sliders.length; i++ ) {      var button = $(sliders[i]).prev('p').find('button')[0];        noUiSlider.create(sliders[i], {        start: 5,        step: 1,        behaviour: 'tap',        connect: [true, false],        range: {          'min':  1,          'max':  10        }      });        attachEvent(sliders[i], button);    }      function attachEvent(slider,button){      slider.noUiSlider.on('update', function( values, handle ) {        button.innerText = parseInt(values[handle]);      });    }    });  

How do I convert this to use UJS to update this record without needing a form?

Rails Geocoder gem & Google Autocomplete API - Query Limit Reached

Posted: 30 Oct 2016 08:09 AM PDT

I have tried to implement Google's autocomplete API, when user types a location and presses to enter, A map with markers load in another page. It looks exactly like Airbnb. Search, then map..

My problem is, lately I am getting an error of "query size limit reached". I have read all the posts about this issue here but could not find a solution.

Basically, when user types an address as string, I get that string and use it for google maps' init lat & long. I use geocoder gem and server as Heroku.

Here is how it looks like;

@search = params[:search]  if !@search.nil? && @search.strip != ""        location =  Geocoder.search(params[:search])      @initlat = location[0].latitude      @initlng = location[0].longitude   end  

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