Sunday, November 27, 2016

Add price label in chartkick.js | Fixed issues

Add price label in chartkick.js | Fixed issues


Add price label in chartkick.js

Posted: 27 Nov 2016 07:35 AM PST

I'm using chartkick to generate a bar chart, with this data that generated via ajax in ruby on rails,

 @data = [               {                 name: "Fruits",                  data: [["2010", 10], ["2020", 16], ["2030", 28]]               },               {                 name: "Meats",                  data: [["2010", 24], ["2020", 22], ["2030", 19]]               },               {                 name: "Vegetables",                  data: [["2010", 20], ["2020", 23], ["2030", 29]]               }             ]   

All I want to ask is how to add like $ label, so in example, the bar label would show 20$ in 2010 for vegetables?

Thanks before.

activeadmin "Object doesn't support this property or method" on admin/login

Posted: 27 Nov 2016 07:35 AM PST

I'm following this tutorial, but I got stuck on an this error:

ExecJS::ProgramError in ActiveAdmin::Devise::Sessions#new

Showing    c:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/bundler/gems/activeadmin-78324a83fa01/app/views/layouts/active_admin_logged_out.html.erb where line #9 raised:    TypeError: Object doesn't support this property or method    Rails.root: c:/Sites/myrubyblog  
  • Ruby directory: C:\RailsInstaller\Ruby2.1.0
  • My app directory: C:\Sites\myrubyblog

Line #9 in active_admin_logged_out.html.erb:

<%= stylesheet_link_tag style, options %>  

Thank you for your time.

Add Objects on Rails Server

Posted: 27 Nov 2016 06:56 AM PST

meanwhile I'm pretty desperate since I can't continue working on my Website. I created a Ruby on Rails server and added a products controller via scaffolding. When I am on my local server, I can add a new product (new object of the product category) with the already given Rails structure. But I want to add the objects/products in my text documents, but where exactly is this possible?

I know I can add a product like so: bike1 = Bike.create ( :name => "Nice Bike" ) But where exactly do I have to add it that it is displayed on the show page of the Product controller?

And is it possible to see my created products in my database folder?

Thank You!

Rails 4: Set enum field through FactoryGirl attributes

Posted: 27 Nov 2016 07:13 AM PST

I have a Model that has an enum as attribute.

class ApplicationLetter < ActiveRecord::Base    belongs_to :user    belongs_to :event      validates :user, :event, presence: true      enum status: {accepted: 1, rejected: 0, pending: 2}    end  

As well as a factory that generates this model and sets a value for the enum

FactoryGirl.define do    factory :application_letter do      motivation "motivation"      user      event      status :accepted    end  end  

In a controller test I want to get valid attributes through the factory

let(:valid_attributes) { FactoryGirl.build(:application_letter).attributes }  

and create a application with these attributes.

application = ApplicationLetter.create! valid_attributes  

But I get the following error:

ArgumentError: '1' is not a valid status

Why is status interpreted as string? If I change the status in the factory I get the same error, but with the right corresponding number.

Align text beneath images

Posted: 27 Nov 2016 06:51 AM PST

Currently I'm working in rails app, https://i.stack.imgur.com/aSr4P.png this is my contributers page, I want name of each members beneath the images on centered. Any help will be apperciated.

Below is my member.html.erb file

<h1>CONTRIBUTORS</h1>     <div id="contributors_image">    <%= image_tag "one.jpg" %>    <%= image_tag "two.jpg" %>    <%= image_tag "three.jpg" %>    <%= image_tag "four.jpg" %>     <%= image_tag "five.jpg" %>     <%= image_tag "six.jpg" %>     <%= image_tag "seven.jpg" %>    </div>  

and my part of application.css.scss is,

#contributors_image {          float: centre;          margin-left: 3em;          img {              width: 200px;              height: 200px;              border-radius: 8.35em;          }      }  

Css file in vendor/assets/stylesheets is not loading

Posted: 27 Nov 2016 07:13 AM PST

application.css in folder app/assets/stylesheets is loading by default without any problem but same file in app/assets/stylesheets/vendor directory is not getting loaded. I have checked my assets paths and vendor/assets/stylesheets is present there.

fields for child_index not changing for nested_attributes

Posted: 27 Nov 2016 05:41 AM PST

I am using nested_attributes for has many associations. The nested attributed is added dynamically.

The association is Invoice has_many Items

Contoller code:

def new    @invoice = Invoice.new    @invoice.items.build      end  

new.html.erb

<%= simple_form_for(@invoice,:format => :js,:method => :post, :post => true,:url => invoices_path, :required => true) do |f|%>     <%= f.fields_for :items do |builder| %>          <%= builder.text_field :fullname %>     <% end %>     <%= f.fields_for :items do |builder| %>          <%= builder.text_field :fullname %>     <% end %>     <script type="text/javascript">         $('#btnAddItemtoInvoice').on('click', function(){               $('.exp').append("<%= escape_javascript(render partial: 'item_fields.html.erb', locals: {f: f}) %>")           })     </script>   <% end %>  

For first two row the child index is incremented properly but for rows from partials are not incremented. Child index I am getting is: 0,1,2,2,2 and so on.

Partial: _item_fields.html.erb

<%= f.fields_for :items do |builder| %>      <%= builder.text_field :fullname %>  <% end %>  

Why the child_index are not incrementing? How can I increment the child_index here?

Rails Assigning a class in html erb works in one place, doesn't work in another

Posted: 27 Nov 2016 05:39 AM PST

I have a view where I make 2 loops to output the information. One as a menu and another as data:

<div class="base-form side-menu">      <ul class="food-groups">        <% @food_categories.each do |category| %>          <li class="<%= "#{Food::CATEGORIES[category]}"%>" data-content=".<%= "#{Food::CATEGORIES[category]}-content"%>">  <%="#{category}"%>  </li>        <% end %>      </ul>    </div>      <div class="base-form main-form">        <% @food_categories.each do |cat| %>        <%= "#{Food::CATEGORIES[cat]}-content" %>          <div class="<%= "#{Food::CATEGORIES[cat]}-content"%>">              <% @foods.where(category: "#{Food::CATEGORIES[cat]}").find_each do |food| %>              <p>                <%= "Name: #{food.name}, portion: #{food.portion}, calories: #{food.calories}" %>              </p>              <% end %>            </div>      <% end %>      </div>  

First loop works fine, each element gets its class correctly. Second loop(with |cat|) works, but the div's don't get any classes assigned. I even copied the class="<%=...%>" to the 't' from the first loop and it still doesn't work! Although just putting the string on the page that I'm also passing as a class works fine. I don't get it!

Rails has_many through

Posted: 27 Nov 2016 07:42 AM PST

A user can create organization and then he can make other users as moderators to his organization. Below method shows how the organization is created.

def create                                                       @organization = current_user.organizations.build(organization_params)      # Confirm organization is valid and save or return error       if @organization.save!      # New organization is saved                                    respond_with(@organization) do |format|                          format.json { render :json => @organization.as_json }        end    else      render 'new', notice: "Unable to create new organization."    end  end    

How should I create moderators for the organization. I tried using has_many through but it failed. Can somebody help me?

Update

Organization Model

class Organization < ActiveRecord::Base    has_many :moderators    has_many :users, :through => :moderators  end  

UserModel

class User < ActiveRecord::Base     enum role: [:user, :moderator, :organization, :admin]     after_initialize :set_default_role, :if => :new_record?       def set_default_role       self.role ||= :user     end       # Include default devise modules. Others available are:     # :confirmable, :lockable, :timeoutable and :omniauthable     devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable       has_many :moderators     has_many :organizations, :through => :moderators   end  

Moderator Model

class Moderator < ActiveRecord::Base    belongs_to :user    belongs_to :organization  end  

When I create new organization my organization user_id is nil?

The action x could not be found for xyzController

Posted: 27 Nov 2016 05:03 AM PST

I'm a beginner in Ruby on Rails and I have a problem. I'm trying to add comments to my app. Everything is working, but when I added this code to routes.rb

resources :galleries do      resources :comments, module: :galleries  end  resources :articles do      resources :comments, module: :articles  end  

I can't update any gallery or article. My whole routes.rb:

Rails.application.routes.draw do        devise_for :users          resources :galleries do          resources :comments, module: :galleries      end      resources :articles do          resources :comments, module: :articles      end        match ':controller(/:action(/:id))(.:format)', via: [:post, :get]          root 'public#index'  end  

Rails Activeadmin multiple images for one table

Posted: 27 Nov 2016 06:03 AM PST

I'm using Rails 5 and activeadmin for admin section. I prepared a basic gallery on frontend and I want to upload more than one image to my gallery.

This is my code :

ActiveAdmin.register Photo do      permit_params :project_id , :image      form html: { multipart: true }  do |f|      f.inputs do        f.input :project_id, as: :select, collection: Project.all.collect {|project| [project.project_name, project.id] }      end        f.inputs "Upload" do        f.input :image,  required: true,  as: :file , input_html: { multiple: true }      end      f.actions    end  end  

It can take multiple photos on html but it does not upload them. But I can upload one photo if I don't add input_html: { multiple: true } code.

How can I upload multiple photos? (I'm using paperclip)

Time.now not changing in partial - rails

Posted: 27 Nov 2016 05:13 AM PST

I am rendering a partial on click event

$('#btnAddItem').on('click', function(){    $('.item_list').append("<%= escape_javascript(render partial:'item_fields.html.erb') %>")  })  

In partial I am trying to print Time.now but I am getting same time, whenever I click the button - '#btnAddItem'

Partial code:

<%= Time.now %>  

Why I am getting same time? How can I get different time each-time I click?

Update: Need to store time.now in ruby variable, which will be used further.

How to update if statement in views through AJAX in Rails app

Posted: 27 Nov 2016 03:59 AM PST

In my app I have votable posts where you vote through AJAX which works fine but I want to update status of the post (whether it is agreed milestone) upon voting through AJAX as well. Status of the post is in views:

<div id="milestone-<%= post.id %>">   <% if post.agreed? %> Agreed Milestone <% elsif post.milestone? %>    Proposed Milestone <% end %>  </div>  

posts_controller.rb

def upvote    @post = Post.find(params[:post_id])    respond_to do |format|      format.html { redirect_to @post }      format.js      @post.upvote_by current_user    end    if @post.votes_for.up.size == count_users        @post.toggle! :agreed    end  end  

upvote.js.erb

$('#voting-<%= @post.id %>').hide();  $('#agreed-<%= @post.id %>').html("<%= j render(partial: 'posts/agreed',  locals: {post: @post}) %>");  

Agreed partial is list of voters.

So when post reaches certain number of votes it changes its boolean agreed to true. I want to then update status in views. I tried rendering milestone element as partial and several other approaches but the if statement is never executed and status does not update.

Does queries per second in MySql really matter?

Posted: 27 Nov 2016 02:10 AM PST

For example, if you were to have a webpage that writes 10 times (5ms each query so relatively inexpensive) to a MySQL database every time you visited the page. Would it be the same thing as a page load that writes only one query that is 50ms instead? What I'm basically asking is does queries per second really matter? Will it bottleneck my database faster?

If I had a pretty large database, is there any differences of writing 10000 inexpensive queries per second versus 1000 more expensive ones?

I am not able to create new app using "rails new blog"

Posted: 27 Nov 2016 03:46 AM PST

I am getting this error during create a new project so where will i add the thor gem version as explained in given duplicate question.

I am getting this error when i am trying to create a new rails application. I am also getting same error when i am running the command rails -v

umesh@umesh-Lenovo-G570:~/work/practice$ rails new blog  /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/parser/option.rb:130:in `validate_default_type!': An option's default must match its type. (ArgumentError)      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/parser/option.rb:113:in `validate!'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/parser/argument.rb:24:in `initialize'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/parser/option.rb:9:in `initialize'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/base.rb:544:in `new'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/base.rb:544:in `build_option'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/thor-0.19.2/lib/thor/base.rb:278:in `class_option'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/base.rb:202:in `class_option'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/app_base.rb:71:in `add_shared_options_for'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/rails/app/app_generator.rb:160:in `<class:AppGenerator>'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/rails/app/app_generator.rb:159:in `<module:Generators>'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/rails/app/app_generator.rb:153:in `<module:Rails>'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/generators/rails/app/app_generator.rb:3:in `<top (required)>'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands/application.rb:2:in `<top (required)>'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/cli.rb:14:in `<top (required)>'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/umesh/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/bin/rails:9:in `<top (required)>'      from /home/umesh/.rvm/gems/ruby-2.3.1/bin/rails:23:in `load'      from /home/umesh/.rvm/gems/ruby-2.3.1/bin/rails:23:in `<main>'      from /home/umesh/.rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `eval'      from /home/umesh/.rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `<main>'  umesh@umesh-Lenovo-G570:~/work/practice$   

How to add image to foundation tooltip

Posted: 27 Nov 2016 12:48 AM PST

i'm using foundation tooltips to show the users which liked the post. For example here i need to show current user avatar:

span.has-tip data-tooltip="" title="#{image_tag(current_user.avatar)}"Like  

But when I reload page i get an tooltip with:

<img src=  

and nothing else. How should I correctly use images in tooltip?

If I call image_tag(current_user.avatar) in other place it works fine.

Ruby on Rails: order records with null value

Posted: 27 Nov 2016 03:35 AM PST

User.where(id: users_ids)      .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1')      .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1')      .select('users.*, names.first_name AS f_name , emails.email AS primary_email')  

I need to order records by f_name. When f_name is nil then records are moved to the end and ordered by email.

Below is the query,

User.where(id: users_ids)      .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1')      .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1')      .select('users.*, names.first_name AS f_name , emails.email AS primary_email')      .where('names.first_name IS NOT NULL')      .order('f_name asc').union(  User.where(id: users_ids)      .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1')      .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1')      .select('users.*, names.first_name AS f_name , emails.email AS primary_email')      .where('names.first_name IS NULL')      .order('primary_email asc'))  

The above query don't work.

Database - MySql

How to set route for a rendered action? Rails

Posted: 27 Nov 2016 12:35 AM PST

i'm new to mvc, rails and web development and i'm facing a problem:

I have an action(show) and a view for this action.

The view for show submits a form_tag to another action, that renders the action show.

The problem is, I have no idea how to set a route for the action that renders show.

Right now my routes.rb is:

resources :meals do    collection do      get "meals/:id", to: "meals#show"    end  end  

Tried to add these but didn't work:

match "meals/:id/calculate" , :to => "meals#calculate",:via => [:get]  

and:

get "meals/:id/calculate", to => "meals#calculate"  

How to address shortcomings of associated model from Rails tutorial

Posted: 27 Nov 2016 03:07 AM PST

I followed the getting started tutorial for Rails which was fine for the most part, but lacked some detail when it came to the associated model (comments):

  1. There was no validation - it's easy enough to add that, but then I wasn't sure how to display the error messages from failed validation.
  2. Using @article.comments.build so you can display the comment form effectively "created" another comment in that session, so if you iterate through all comments, there'd be an extra blank one because of that. It's just a coincidence that the guide listed the comments before that line of code was executed, and thus didn't encounter the problem.

Whilst I tried something for 1. (which will be detailed below), I've no idea how to go about solving 2. - it probably belongs in its own question, but I'm not even sure how to name it.

Attempt at validation/error display

I tried to basically apply the same strategy for displaying error messages with the articles, again for the comments. I knew there'd be some extra complexity, but I tried to navigate it logically. This is what I changed:

app/models/comments.rb

class Comment < ApplicationRecord    belongs_to :post      validates :commenter, presence: true    validates :body, presence: true  end  

app/controllers/comments_controller.rb

class CommentsController < ApplicationController    def create       @article = Post.find(params[:article_id])      @comment = @article.comments.new(comment_params)        if @comment.save        redirect_to article_path(@article)      else        render 'articles/show'      end    end      def destroy      ...  

app/views/comments/_form.html.erb

<%= form_for([@article, @article.comments.build]) do |f| %>    <% if self.instance_variable_defined?('@comment') and @comment.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@comment.errors.count, 'error') %> occurred:</h2>        <ul>          <% @comment.errors.full_messages.each do |msg| %>            <li><%= msg %></li>          <% end %>        </ul>      </div>    <% end %>      <p>      <%= f.label :commenter, 'Your Name' %>      ...  

Whilst this successfully displayed the error messages, the following problems occurred:

  1. Because it uses render instead of redirect, the user ends up on a URL that normally can't serve GET requests (i.e. /posts/1/comments) - this is strange, because if the page loads again it'll 404. I can't use redirect though, because then the attempted comment creation (with the error messages) will be lost.
  2. Presumably because @article.comments.new has been executed prior to rendering, the same problem as that which was described in 2. above (regarding @article.comments.build) occurs: a blank comment is displayed.

So that's where I'm stuck. These are pretty basic problems - the system wouldn't be whole without them, and yet I'm lost for what the proper solution would be.

How can I display these errors whilst avoiding the above problems?

Rails view, undefined method `empty?' for a datetime object

Posted: 26 Nov 2016 11:35 PM PST

So i was modifying my index view as to make it only render specific fields based on an instance variable named fields, but when i did this it worked just fine except for the datetime field that generates an error. example :undefined method empty?' for Tue, 22 Nov 2016 23:01:00 +0000:DateTime Here's the view code.

<p id="notice"><%= notice %></p>    <h1>Articles</h1>    <table>    <thead>      <% @fields = ["headline", "content","date", "locale", "classification" ]  unless @fields.present? %>      <tr>        <% @fields.each do |field| %>          <th><%= "#{field.titleize}" %></th>        <% end %>      </tr>    </thead>      <tbody>      <% @articles.each do |article| %>        <tr>          <% @fields.each do |field| %>          <td><%= simple_format article.send(field) %></td>          <% end %>          <td><%= link_to 'Show', article %></td>          <td><%= link_to 'Edit', edit_article_path(article) %></td>          <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>    </tbody>  </table>    <br>    <%= link_to 'New Article', new_article_path %>  

And here's the model code

class Article    include Mongoid::Document    validates :classification,      :inclusion  => { :in => [ 'unclassified', 'medical', 'non medical'] }    validates :headline, presence: true    validates :content, presence: true    field :headline, type: String    field :content, type: String    field :classification, type: String    field :weak_classification, type: String    field :locale, type: String    field :date, type: DateTime  end  

How can i fix this issue?

Google docs with rails

Posted: 26 Nov 2016 11:24 PM PST

I am new to rails and I am looking to integrate google docs with an existing rails project. I want to create a new google doc for a user when he clicks on a button. Are there any pre-existing gems for the same? Any help will be appreciated

React on Rails Gem - Foreman Thor Conflict

Posted: 27 Nov 2016 12:17 AM PST

I've been trying to implement the react_on_rails gem using the tutorial found here.

Difference being I'm using ruby 2.3.3, node 7.2.0, and ran the setup with redux (rails generate react_on_rails:install --redux)

However now when I try to run foreman foreman run -f Procfile.dev I get the following error:

/Users/ryanking/.rvm/gems/ruby-2.3.3/gems/thor-0.19.3/lib/thor/base.rb:534:in `thor_reserved_word?': "run" is a Thor reserved word and cannot be defined as command (RuntimeError)      from /Users/ryanking/.rvm/gems/ruby-2.3.3/gems/thor-0.19.3/lib/thor/base.rb:597:in `method_added'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/gems/foreman-0.82.0/lib/foreman/cli.rb:80:in `<class:CLI>'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/gems/foreman-0.82.0/lib/foreman/cli.rb:11:in `<top (required)>'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/gems/foreman-0.82.0/bin/foreman:5:in `require'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/gems/foreman-0.82.0/bin/foreman:5:in `<top (required)>'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/bin/foreman:22:in `load'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/bin/foreman:22:in `<main>'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval'      from /Users/ryanking/.rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `<main>'  

Any idea why this is happening & how I could fix it?


Procfile.dev contains:

web: rails s -p 3000  client: sh -c 'rm app/assets/webpack/* || true && cd client && npm run build:development'  

Which I can run fine from the command line but not with foreman.

Showing comment feed of current_user and friends with acts_as_commentable_with_threading gem

Posted: 26 Nov 2016 10:03 PM PST

I'm using the gem acts_as_commentable_with_threading. I have 3 models User, Group and i have Comment associated with both models. Users are able to right comments in their profile just as twitter and facebook have but i'n a more simple form. Users are also able to follow each other and ones they do follow each other their comments show as a feed in each profile.

In my controller i have this. The code below is what i would believe would show the feed i want, but it just shows the comments from the current user.

def show   @comments = current_user.comment_threads.where(user_id: current_user.following_users.ids + [current_user])  end  

Anything i'm doing wrong here? Any suggestions would help

Why does order of migrations matter in Heroku Postgres but not local Postgres database?

Posted: 26 Nov 2016 09:42 PM PST

I was having a hell of a time earlier trying to figure out why Heroku couldn't run my migrations. It kept complaining that a reference did not exist.

For my first migration, I referenced a table that hadn't been created yet using a foreign key. In order to solve this problem, I had to arbitrarily modify the timestamps of the migration files so that no table would be created before a table it depends on (references).

Amazingly, this solved the problem with running the migrations on Heroku and they eventually ran without error. Also, the migrations would run perfectly on my development machine, even with the tables that have dependencies being created before the referenced tables exist.

Why did it work on my local database and not on the Heroku database? Is there something I can do next time this happens? It seems really ridiculous to have to always create migrations in order of their dependency in order to please Heroku. I must be missing something, no?

SystemStackError (stack level too deep) for attr_encrypted gem

Posted: 26 Nov 2016 09:41 PM PST

I am using attr_encrypted gem to encrypt my password field of database. I am below code in my model and have only one password field in database.

class User < ActiveRecord::Base  attr_encrypted :password, key: '51E63B44', prefix: ''  end  

I am getting below error log.

SystemStackError (stack level too deep):    app/controllers/api/users_controller.rb:201:in `create'        Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/actionpack-4.2.5.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (104.9ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/actionpack-4.2.5.2/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (28.5ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/actionpack-4.2.5.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (14.7ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/actionpack-4.2.5.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (218.0ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.4ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (1.5ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.4ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (71.7ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)    Rendered /home/hareram/.rvm/gems/ruby-2.3.0@rcp/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (160.4ms)  

I want to encrypt password without adding or modifying my existing database.

Can it be possible using this gem ?

Thanks, Hare

How to implement an index like action, that limits the fields displayed depending on user parameters?

Posted: 27 Nov 2016 05:53 AM PST

I want to implement an action that functions just like index, but with the catch being that if the in the request URL, it specifies that it wants field 1 and field 2, it should only render field 1 and field 2.

Now this would be trivial if it's only done for a JSON response, but how do I implement this for HTML views too ?

The only way I can think of is having a separate view for each combination of fields, but that would be insane. Surely there must be a way that I am completely oblivious of to implement this.

What does resource mean in Devise?

Posted: 26 Nov 2016 08:56 PM PST

I want to change what happenes in devise when a user logs in.. When I look at the source code the word resource is everywhere, but I can't understand what it is a stand in for. Does it only pertain to devise and warden?

def after_sign_in_path_for(resource)    stored_location_for(resource) ||      if resource.is_a?(User) && resource.can_publish?        publisher_url      else        super      end  end  

Statement Invalid in DoorKeeper Error

Posted: 26 Nov 2016 08:57 PM PST

I am getting a peculiar error when using Doorkeeper in my rails app. Here is what my doorkeeper.rb file looks like:

  Doorkeeper.configure do    # Change the ORM that doorkeeper will use (needs plugins)    orm :active_record      # This block will be called to check whether the resource owner is authenticated or not.    resource_owner_authenticator do |routes|      # Put your resource owner authentication logic here.      # Example implementation:      User.find_by_id(session[:user_id]) || redirect_to(routes.login_url)    end    end  

When I go to the route localhost:3000/oauth/authorize with my logged in user it throws this error:

    ActiveRecord::StatementInvalid in Doorkeeper::AuthorizationsController#new          Could not find table oauth_application          def table_structure(table_name)            structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA')            raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?            table_structure_with_collation(table_name, structure)          end  

Could anyone tell me why this error might be occuring?Thanks in advanced for the help.

Clickable text for radio button on Rails

Posted: 26 Nov 2016 08:18 PM PST

  <%=form_for @link do |f| %>    <%=  f.collection_radio_buttons :title, [['💩'] ,['😊'],['😡'],['😏'],  ['🙃']], :first, :last%>      <%= f.submit 'Save'%>  

I'm trying to make the the emojis of my radio buttons clickable (instead of clicking the circle button I want to click the actual emoji).

Then, I want to get rid of the little circle buttons so all that can be seen is the emojis.

Finally, I want there to be some sort of visual signal when one of the emojis is chosen, such as a highlight, since the actual radio button will be gone.

I'm using the simple_form gem. I've searched for days but can't figure out how to do this. Thank you so much for your help!

Using Angular, Trying to Save An Array to the Rails Backend

Posted: 27 Nov 2016 07:34 AM PST

I tried several methods I found online but none worked and they weren't specifically targeting the problems I'm having. Basically I have a recipes Rails app, and using Angular, I have to:
(1) Allow the user to add one or more ingredients and directions in the form, like this: http://jsfiddle.net/V4BqE/
(2) Save the ingredients and directions as an array data type in the Rails database (I'm using postgresql), sort of like this but without using $scope: How to create an Array with AngularJS's ng-model

Schema:

  create_table "recipes", force: :cascade do |t|      t.string   "title"      t.integer  "difficulty"      t.integer  "time"      t.integer  "servings"      t.string   "description"      t.string   "ingredients",              array: true      t.string   "directions",               array: true      t.integer  "category_id"      t.integer  "author_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end  

Controller:

(function() {      'use strict';        function NewRecipeController ($location, RecipeService, CategoryService) {          var vm = this;            CategoryService.getCategories()              .then(function(response) {                  vm.categories = response.data;              });          vm.addRecipe = function() {          var data = {              title: this.title,              difficulty: this.difficulty,              time: this.time,              servings: this.servings,              description: this.description,              // Im stuck trying to figure out the following 2 lines              ingredients: this.ingredients,              directions: this.directions,              category_id: this.category.id          };            RecipeService.createRecipe(data);          $location.path('profile');        };        }        angular          .module('app')          .controller('NewRecipeController', NewRecipeController)    }());  

Form (just the ingredients and directions section are relevant):

        <form name="newRecipe" novalidate ng-submit="vm.addRecipe()">                <!-- title -->                <div class="form-group">                <label for="title">Recipe Name</label>                <input class="form-control" type="text" name="title" ng-model="vm.title" required>              </div>                <!-- category -->                <div class="form-group">                  <label for="category">Category</label>                <select class="form-control" name="category" ng-model="vm.category" ng-options="category.name for category in vm.categories" required></select>              </div>                <!-- description -->                <div class="form-group">                  <label for="description">Description</label>                <input class="form-control" type="text" name="description" ng-model="vm.description" required>              </div>                <!-- difficulty -->                <div class="form-group">                <label for="difficulty">Difficulty</label>                <input class="form-control" type="number" name="difficulty" ng-model="vm.difficulty" min="1" max="5" required>                <small id="emailHelp" class="form-text text-muted">Enter a number between 1 and 5.</small>              </div>                <!-- time -->                <div class="form-group">                  <label for="time">Time to Make (Minutes)</label>                <input class="form-control" type="number" name="time" ng-model="vm.time" min="5" step="5" required>                <small id="emailHelp" class="form-text text-muted">Enter a number that is an increment of 5 minutes.</small>              </div>                <!-- servings -->                <div class="form-group">                  <label for="servings">Servings</label>                <input class="form-control" type="number" name="servings" ng-model="vm.servings" required>              </div>                <!-- ingredients - this is where I'm stuck -->              <!-- I want to be able to let the user add more input fields if they want and do the same for directions -->                <div class="form-group" ng-repeat="ingredient in vm.ingredients">                  <label for="ingredients">Ingredients</label>                <input class="form-control" type="text" name="ingredients" ng-model="vm.ingredients[$index]" required>              </div>                <div ng-show="newRecipe.$valid">                  <input class="btn btn-primary" type="submit" value="Create Recipe">              </div>          </form>  

I understand that I have to save the array as a string. I tried directly saving ingredients: '["ingredient1", "ingredient2"]' and ingredients: '["ingredient1, ingredient2"]', but both just saved as ingredients: ["ingredient1"]. I've also tried JSON.stringify(ingredients). I am using a serializer:

class RecipeSerializer < ActiveModel::Serializer    attributes :id, :title, :difficulty, :time, :servings, :description, :ingredients, :directions      belongs_to :category    belongs_to :author, class_name: 'User'    # has_many :favorites      has_many :favorited_users, through: :favorites, source: :user  end  

Recipe Rails controller #create:

  def create      @recipe = Recipe.new(recipe_params)      @recipe.author = current_user      @recipe.save    end  

Full code on Github: https://github.com/auranbuckles/world-recipes

No comments:

Post a Comment