Friday, June 3, 2016

Use data from database in Chart.js/Rails | Fixed issues

Use data from database in Chart.js/Rails | Fixed issues


Use data from database in Chart.js/Rails

Posted: 03 Jun 2016 07:10 AM PDT

I want to show a line chart on my "Weights" index page with Chart.js in my Rails app (a weight loss app). I have a table that holds a user's weight (as "kilograms") for each day (as "day"). I am able to show a line chart, however, but only with static data - not with the data from my Weights table.

What I want to do now is to have "day" on the x-axis and "kilograms" on the y-axis.

How can I achieve this? And as I just started coding few months ago: how should the code look like?

Thx a lot.

This is the code from my weights index.html.erb:

<canvas id="myChart" width="400" height="200"></canvas>  <script>  var ctx = document.getElementById("myChart");  var myChart = new Chart(ctx, {      type: 'line',      data: {          labels: ["day 1", "day 2", "day 3", "day 4", "day 5", "day 6"],          datasets: [{              label: 'My Weight',              data: [82.4, 79.6, 79.3, 78.4, 77.5, 75.1],              backgroundColor: [                  'rgba(0, 0, 0, 0.1)',              ],              borderColor: [                  'rgba(0,0,0,0.9)',              ],              borderWidth: 1          }]      },      options: {          scales: {              yAxes: [{                  ticks: {                      beginAtZero:false                  }              }]          }      }  });  </script>  

rails creating relationships between 2 existing models

Posted: 03 Jun 2016 07:18 AM PDT

I have 2 models:

Account  Profile  

creating these models created 2 tables in the database:

accounts  profiles  

now I want to add a relationship:

  • each account can have many profiles
  • each profile belongs to one account

I ran the following command:

rails g migration AddAccountToProfiles account:references  

which created the following migration:

class AddAccountToProfiles < ActiveRecord::Migration    def change      add_reference :profiles, :account, index: true, foreign_key: true    end  end  

now I'm a little confused:

why does the migration say :profiles and :account? Shouldn't it be :accounts (plural)?

also, after (or before) creating this migration, I have to add belongs_to and has_many in the appropriate model class right?

as a side question, is there a way to add belongs_to and has_many in the models, and from that information have rails generate the appropriate migration without me manually creating a migration with the 'rails g migration ...' command?

Should I default jsonb to '{}' or {} in migration

Posted: 03 Jun 2016 07:18 AM PDT

Of the scarce instructions I've read about adding Postgres's data type jsonb in a migration, it's looking like this:

create_table :ref_check_ins do |t|    t.jsonb :document, null: false, default: '{}'    t.index :document, using: :gin  end  

But is there any reason against defaulting to Hash intead of String, i.e. {} instead of '{}' ?

When defining it to String type, the class of that column:

String < Object  

When defining it to Hash type, the class of that column:

Hash  

Activerecord query with group on multiple columns returning a hash with array as a key

Posted: 03 Jun 2016 07:05 AM PDT

I wrote an ActiveRecord query to fetch count of some data after grouping by two columns col_a and col_b

result = Sample.where(through: ['col_a', 'col_b'], status: [1, 5]).where("created_at > ?", 1.month.ago).group(:status, :through).count

This returns:

{[1, "col_a"]=>7, [1, "col_b"]=>7, [5, "col_a"]=>4, [5, "col_b"]=>1}

Now my question is, how do I access the values in this hash?

Doing something like results[1, "col_a"] throws an error (wrong no. of arguments). I know I can do this by writing a loop and extracting the values one by one.

However I want to know if there is a more idiomatic way to access the values, something similar to results[1], maybe?

Ruby form parameters are null

Posted: 03 Jun 2016 06:44 AM PDT

I'm completely newbie to ruby, and my boss put me to develop a new module in a ruby system.

I just need to create a new page in the dashboard to create some "Service Plans", is just a name, discount percentage and a list of services. I looked how they created other pages and tried to copy them.

My page is almost EXACTLY the New Professionals page. I created a form.haml, a model, a controller and a Plan Form class (they use it to validate the form.)

But when I try to use some parameters in the Plan Form class, they are just nil!

Here is my code:

Plan Class Plan Controller My partial Form.haml My PlanForm Class where the posted date should be validated My console with the Result and messages The rest of result, and we can see that in the line Parameters: the services id's are there!!

Images legends: 1 - My Plan Class 2 - My Plan Controller 3 - My partial _form haml 4 - My Plan Form Class where the posted date should be validated and saved. 5 - My console with the Result and messages 6 - The rest of result. Look at parameters line: the services id's are there! > how can I access them?

My questions are: First: My classes are exactly the same, why doesn't it work?

Second: How can I access the Parameters inside the Plan Form class?

Third: Are there any other better way to do that?

Thank you very much guys! Sorry for the mistakes/wrong format, is my first question here.

Rails token authentication with API. Where does the token go?

Posted: 03 Jun 2016 06:20 AM PDT

First of all, I am fairly new to Rails and this is the first time I'm trying to use a token based authentication process!

So, in my sessions_controller (client app) I have this snippet to fetch the user token from my Rails API:

#basic auth  uri_tk = URI.parse("http://localhost:3000/token")    http = Net::HTTP.new(uri_tk.host, uri_tk.port)  request = Net::HTTP::Get.new(uri_tk.request_uri)  request.basic_auth(params[:session][:email], params[:session][:password])  response = http.request(request)  

And on my application_controller (api app) I have this:

class ApplicationController < ActionController::API     include ActionController::HttpAuthentication::Basic::ControllerMethods   include ActionController::HttpAuthentication::Token::ControllerMethods     before_filter :authenticate_user_from_token, except: [:token]     include Authenticable     respond_to :json     def token    authenticate_with_http_basic do |email, password|      user = User.find_by(email: email)      if user &&  user.match_password(password)        render json: {token: user.auth_token}      else        render json: {error: 'Incorrect credentials' }, status: 401      end    end   end     private      def authenticate_user_from_token      unless authenticate_with_http_token { |token, options| User.find_by(auth_token: token)}         render json: {erro: 'Bad Token'}, status: 401      end    end    end  

So, my problem is: when we reach the point where all subsequent requests need to pass through "authenticate_user_from_token", there is no token to authenticate from. Should I store the token in the client session? Do I have to specify the token in every request I make?

Thanks in advance!

ruby on rails virus using server for ddos

Posted: 03 Jun 2016 05:57 AM PDT

How to clean ruby on rails app if I've been infected with some virus that uses my DigitalOcean server to send outgoing traffic? Probably for ddos attacks.

I just made new droplet with all security updates, but when I run bunndle install it started to spit large traffic.

How to use the selected date on the previous page?

Posted: 03 Jun 2016 06:46 AM PDT

How to use the selected date on the previous page?

We get the value date:

<%= form_tag :action => 'method_name' do %>    <%= text_field_tag('datetimepicker12', nil, options = { :onchange => "this.form.submit()"}) %>    <% end %>  

Controller:

def  selectday     end    def method_name    @date=params[:datetimepicker12]    redirect_to selectday_path(@date)  end  

view selectday receives parameters:

Request    Parameters:    {"format"=>"24-06-2015"}  

Here it is necessary to print the selected date. Call object in selectday view, but no output it:

<span> <%= @date %></span>  

I am facing the routing error in rails as uninitialized constant UserController

Posted: 03 Jun 2016 05:52 AM PDT

I am going create a rail application which takes input from an csv file and show it on the webpage.

After doing all the needful stuffs I am facing this: Routing Error

uninitialized constant UserController

My app\controllers\users_controller.rb file is:-

class UsersController < ApplicationController     def index      @users=User.all     end       def import      User.import(params[:file])      redirect_to root_url, notice: "Activity data imported!"     end  end  

My app\model\user.rb file is:- class User < ActiveRecord::Base require 'csv'

  def self.import(file)      CSV.foreach(file.path, headers:true) do |row|          User.create! row.to_hash      end    end  end  

My app/views/users/index.html.erb file is:-

 <%= flash[:notice] %>     <table>   <thead>      <tr>          <th>Name</th>          <th>Name</th>      </tr>   </thead>    <tbody>      <% @users.each do |user| %>      <tr>          <td><%= user.user %></td>          <td><%= user.age %></td>      </tr>      <% end %>  </tbody>  </table>    <div>  <h4>Import the data!</h4>  <%= form_tag import_users_path, multipart: true do %>  <%= file_field_tag :file %>  <%= submit_tag "Import CSV" %>  <% end %>  </div>  

My config\routes.rb file is:-

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

I have not posted any #marked commented line from routes.rb file here. The snapshot of the output screen is here:- when clicking on the import csv button the following error is shown: enter image description here enter image description here

How to manage statuses associations in rails

Posted: 03 Jun 2016 05:54 AM PDT

Say for example I have an Order and Status.

Status:

  1. status_id: 1 , status_name: Open
  2. status_id: 2 , status_name:Closed

Order:

  1. order#: 1, status_id: 1

How to manage the association in Ruby on Rails?

Would the following code is the best choice?


class Status < ActiveRecord::Base          has_many :orders    end    class Order < ActiveRecord::Base          belongs_to :status    end  

Rails - Do not send message if user not approved

Posted: 03 Jun 2016 05:26 AM PDT

I have a rails app and user model. User can sign up the form but the admin should approved his/her profile first. So I have status :boolean default to false column in user model. You can search user on search field. I do not show those users if status column is false.

BUT Lets say user with an id 5 is not approved meaning status column is false.

if user types .../en/users/5

it goes to that url and can send messages. How should I do that so they cant send email.

I should have something like;

def check_user(user)    if user.status       redirect_to root_path    end  end  

and where should I put this?. To user controller#show action as before filter?

Rails Can't verify CSRF token authenticity ajax with X-CSRF-TOKEN header

Posted: 03 Jun 2016 04:57 AM PDT

I try to register a service worker endpoint in my database but when I send my post data with fetch the app raise an error.

I want to keep the csrf verification. Do you see something wrong ?

            var ready;                ready = function(){                if ('serviceWorker' in navigator) {                 console.log('Service Worker is supported');                  navigator.serviceWorker.register('/service-worker.js').then(function(reg) {                     reg.pushManager.subscribe({                       userVisibleOnly: true                   }).then(function(sub) {                       console.log('endpoint:', sub.endpoint);                       console.log(sub);                       var token = $('meta[name=csrf-token]').attr('content')              console.log(token);                         return fetch('/register_endpoint', {                      method: 'post',                      headers: {                        'Content-type': 'application/json',                        'X-CSRF-TOKEN': token                      },                      body: JSON.stringify({                        endpoint: sub.endpoint,                        authenticity_token: token                        })                    });                   });                     }).catch(function(err) {                   console.log('Erreur -> ', err);                 });                }                };                    $(document).ready(ready);              $(document).on('page:load',ready);  

thanks

How to make notice when image gets uploaded with Paperclip

Posted: 03 Jun 2016 05:09 AM PDT

Is there any way to include a notice on a page like "Successfully Uploaded" when image gets uploaded with Paperclip?

Avatar upload is part of my simple form here is a current code:

<div class="img-circle">           <%= profile_avatar_select(@user) %>      </div>      <%= f.input :avatar, as: :file, label: "false" %>        </div>  

my application_helper.rb

def profile_avatar_select(user)      return image_tag user.avatar.url(:medium),                     id: 'image-preview',                     class: 'img-responsive img-circle profile-image' if user.avatar.exists?    image_tag 'default-avatar.png', id: 'image-preview',                                    class: 'img-responsive img-circle profile-image'  end    

and in user.rb:

has_attached_file :avatar, styles: { medium: '152x152#' }    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/    end  

Converting array/hash to string and converting that string back to array/hash in ruby

Posted: 03 Jun 2016 04:28 AM PDT

I had this array lets say,

array = [{'key' => 0},1]  

so now array[0]['key'] has value 0. When I convert it to string like this:

array.to_s  

Now the array is not an array its a string which is like this:

"[{'key' => 0},1]"  

If I do array[0] now, it will output [

I want to convert this back to array so that I can use array[0]['key'] again.

Full Code:

array = [{'key' => 0},1]  array = array.to_s  puts array[0]['key'] #Should output 0 but it does not output anything  

The thing is that I have already saved stuff like that in the database, so now I need to use that stuff back, so the only way is to parse the saved string (which was actually an array).

Rails DataTables warning Ajax error please see http://datatables.net/tn/7

Posted: 03 Jun 2016 04:14 AM PDT

Im using ruby on rails with datatables, When i type in the search box, it pops up this error

DataTables warning: table id=feedbacks - Ajax error. For more information about this error, please see http://datatables.net/tn/7  

Here is my code:

index.html.slim https://gist.github.com/anonymous/8953b680e4dfe6f2e6d739f1e13f029b

datatable feedbacks.rb https://gist.github.com/anonymous/823ce636c5f4fb8cdc8e42557ec6353b

What is the problem ?

Rails, "undefined method `variant' for nil:NilClass" on render json

Posted: 03 Jun 2016 04:37 AM PDT

I am trying to do something really simple, render a json with some stuff. I do have a view views/api/initialize.html.erb if this counts as useful info. I have no idea what causes this but the variables filled alright, I checked

My controller:

class ApiController < ApplicationController      def initialize            @articles = Article.all          @areas = Area.all          @languages = Language.all          data_json = { articles: @articles, areas: @areas, languages: @languages }            render json: data_json          end        def index        end    end  

My route:

get '/init', controller: 'api', action: 'initialize'

Here is my full error trace from development.log:

NoMethodError (undefined method `variant' for nil:NilClass):    app/controllers/api_controller.rb:9:in `initialize'    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (3.9ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (14.1ms)    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (44.1ms)  DEPRECATION WARNING: Accessing mime types via constants is deprecated. Please change `Mime::HTML` to `Mime[:html]`. (called from const_missing at /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/http/mime_type.rb:52)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.4ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.4ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.4ms)  DEPRECATION WARNING: Accessing mime types via constants is deprecated. Please change `Mime::WEB_CONSOLE_V2` to `Mime[:web_console_v2]`. (called from const_missing at /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/http/mime_type.rb:52)    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (36.5ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.4ms)    Rendering /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)    Rendered /usr/local/lib/ruby/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (59.3ms)  

Can you locate where the problem is here? Thank you.

How can show current_user's friends' posts and what's popular in one record?

Posted: 03 Jun 2016 04:19 AM PDT

I have set up my scopes and all are working as expected but I could find a way to filter the friends posts in one scope. In the model

scope :popular, ->{ where("cached_votes_up > '20'") } # change this to a much bigger number overtime  scope :following, ->{ where(Post.current_user.following.ids.include? user_id) }  scope :ordered, -> { order(created_at: :desc) }  

In the controller

@post = Post.ordered.popular.following.paginate(:per_page => 10, :page => 1)  

How can I add the following/friend filtering for a scope so i can merge them with other scopes.

I'm trying to make the page display posts with more than 20 likes and also display friends' posts even if they're not above 20.

Thanks in advance.

undefined method contact_path in rails form

Posted: 03 Jun 2016 05:02 AM PDT

I have my routes defined as below

get 'contacts/new', to: 'contacts#new'  

And in my ContactsController I have defined as below

def new    @contact = Contact.new  end  

In views contacts/new/_form.html.erb I have structured form as below

<%= form_for @contact, html: {multipart:true} do |f|  %>    <%= f.label :username %>  <%= f.text_field :username %>    <% end %>  

But when i go to localhost:3000/contacts/new

I get the below error.

undefined method contacts_path which is occuring in first line of form.

But when i try to define as below in routes, it worked

get 'contacts/new', to: 'contacts#new', as: 'contact'  

Any idea why rails throws such error when i have defined it in the routes file. I am just trying to understand inner workings of rails routes

Ruby on Rails - Adding sort order to album images

Posted: 03 Jun 2016 04:09 AM PDT

I am creating a users album application. User can upload many images into their album and I am using nested_forms for uploading images to album.

In my view when user is seeing the images that belongs to the album I want to show X of (total_number_of_images).

For ex: if a album has 12 images and user is seeing the 3rd image in that album, it would be 3 of 12 and when they click on next it would change to 4 of 12, etc.

Please see attachment enter image description here

How can I get this to work? Do I need to add a column in images-db (how to add the sort order) or there is other ways to do so?

This is what I have done until now: I have added a sort_order column in images-db and does this:

class Image < ActiveRecord::Base  after_create :previous_slide    @slide = user.images.order("id DESC")    @slide.find_each do |slide|     slide.increment!(:sort_order, + 1)    end    end  

This actually adds increment to sort_order column but in wrong order since the order is always id ASC no matter what I have added myself. I get:

id    sort  1      4  2      3  3      2  4      1  

Its has to be:

id    sort  1      1  2      2  3      3  4      4  

As you can see its on wrong order.

Ruby on rails web application

Posted: 03 Jun 2016 03:39 AM PDT

If I want to build web application that the server side will be in ruby on rails, I need to learn ruby language in order to that?

I need to mentioned that I am new to ruby and to ruby on rails. In addition I will be happy for a short explanation what I need to do first in order to do the right steps.

Thanks!!!

Boolean value in RAIL API

Posted: 03 Jun 2016 06:41 AM PDT

I have created RAILS API where I am sending Boolean value True(true) or False(false). Application works fine if I send "true" value in boolean field but it throws error message i.e "Filed can't be null" if I pass "false". Please find the below example-

{ "Product": {"Name": "product1" , "Active":false} }

{ "Active": [ "can't be blank" ] }

{ "Product": {"Name": "product1" , "Active":true} }

success Message

binding_of_caller gem error in Rails 3.2.13

Posted: 03 Jun 2016 05:26 AM PDT

I am working on Rails 3.2.1 application and this is my Gemfile:

group :development do      gem 'binding_of_caller'      gem 'meta_request'  end  

While running bundle install, I got the following error:

An error occurred while installing binding_of_caller (0.6.8), and Bundler cannot continue. Make sure that gem install binding_of_caller -v '0.6.8' succeeds before bundling.

With some R & D, I run bundle update binding_of_caller, this time it's different error:

An error occurred while installing eventmachine (1.0.0), and Bundler cannot continue. Make sure that gem install eventmachine -v '1.0.0' succeeds before bundling.

Rails_Admin select tag for n-n association

Posted: 03 Jun 2016 03:25 AM PDT

I have 3 models:

# app/models/patient.rb  class Patient < ActiveRecord::Base    has_many :addresses, dependent: :destroy    accepts_nested_attributes_for :addresses, allow_destroy: true  end    # app/models/address.rb  class Address < ActiveRecord::Base    belongs_to :patient    has_and_belongs_to_many :address_types  end    # app/models/address_type.rb  class AddressType < ActiveRecord::Base    has_and_belongs_to_many :addresses  end  

Explanation:

  • Patient can have 0 to N number of Addresses and it is nested in the form.
  • An Address belongs exclusively to a Patient.
  • I categorize (tag) my Addresses by AddressTypes.
    • The AddressTypes will appear as a dropdown field for every Address.
    • There can only be 1 AddressType per Address.
    • An AddressType can be one of the ff: home, office, business, billing, mailing, dormitory, etc.
    • I used has_and_belongs_to_many as the relationship between Address and AddressType because I do not want the AddressType to belong exclusively to a single address. I want an address to be tagged per type though.

What I'm Looking for:

In the rails_admin gem, HTML elements that represent the fields are automagically supplied by inferring the data type and association used. Since AddressType has_and_belongs_to_many Address, the automatic fields that are being shown is this:

new address type

Notice that when you create a new AddressType record, you are allowed to add 1 or more addresses.

How can I replace the n-n widget with a select tag? I already used the enumeration smart default approach like this:

class Address < ActiveRecord::Base      def address_types_enum      AddressType.all.pluck(:name, :id)    end    end  

It actually shows up, but it doesn't save. It throws an error.

Ruby cannot JSON.parse(file.to_json)

Posted: 03 Jun 2016 05:40 AM PDT

I have a hash in a text file, but I'm getting a JSONParseError 757 when I run the below command.

file = File.open("output.txt", "r")  test = JSON.parse(file.to_json)  

However, my test works when I manually type in the hash i.e.

test = JSON.parse(({test=>test}).to_json)  

Any ideas?

Rails: How to start thin server in ssl

Posted: 03 Jun 2016 03:03 AM PDT

I am trying to start thin serve on https protocol but getting below error.

Below is the command that i am using for thin server to start thin server in https

E:\demo1>thin start --ssl --ssl-verify --ssl-key-file E:/demo1/server.key --ssl-cert-file E:/demo1/server.crt  

Below is the error that i am getting.

C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/thin-1.7.0/lib/thin/runner.  rb:147:in `parse!': invalid option: --ssl-verify (OptionParser::InvalidOption)          from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/thin-1.7.0/lib  /thin/runner.rb:50:in `initialize'          from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/thin-1.7.0/bin  /thin:6:in `new'          from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/thin-1.7.0/bin  /thin:6:in `<top (required)>'          from C:/RailsInstaller/Ruby2.0.0/bin/thin:23:in `load'          from C:/RailsInstaller/Ruby2.0.0/bin/thin:23:in `<main>'  

Rails error while migrating to heroku

Posted: 03 Jun 2016 02:58 AM PDT

when I try to migrate to heroku by heroku run rake I get:

Running rake on ⬢ friends-clique... up, run.8185 /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-4.0.0.alpha3/lib/bootstrap/version.rb:2: warning: already initialized constant Bootstrap::VERSION /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-sass-3.3.6/lib/bootstrap-sass/version.rb:2: warning: previous definition of VERSION was here /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-4.0.0.alpha3/lib/bootstrap/version.rb:3: warning: already initialized constant Bootstrap::BOOTSTRAP_SHA /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-sass-3.3.6/lib/bootstrap-sass/version.rb:3: warning: previous definition of BOOTSTRAP_SHA was here DEPRECATION WARNING: The configuration option config.serve_static_assets has been renamed to config.serve_static_files to clarify its role (it merely enables serving everything in the public folder and is unrelated to the asset pipeline). The serve_static_assets alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in at /app/config/environments/production.rb:82) Abort testing: Your Rails environment is running in production mode!

I thought heroku runs in production mode , What just happened .

Redirect_to not working as expected

Posted: 03 Jun 2016 03:10 AM PDT

I'm creating a checkbox with Ajax call to update an attribute... everything is working fine but my redirects aren't working as intended (nor flash[:notices])

If i use chrome Network i can see the GET method for the desired page but no redirect whatsoever and flash[:notices] don't work (I'm assuming it's related)

So Here's my code:

Controller :

def toggle    @prato = Prato.find(params[:id])    if params[:sugestao]     @sugestao = params[:sugestao]    if @sugestao == "true" and Prato.where("sugestao = ? AND categoria_pratos_id = ?", "1" , @prato.categoria_pratos_id).count <= 2   @prato.update_attributes(:sugestao => @sugestao)    else    if @sugestao == "true" and Prato.where("sugestao = ? AND categoria_pratos_id = ?", "1" , @prato.categoria_pratos_id).count > 2    flash[:notice] = "nao"    end  end  if @sugestao == "false"     @prato.update_attributes(:sugestao => @sugestao)    end  end      if params[:menu]    if @prato.update_attributes(:menu => params[:menu])        else      end  else     if params[:ativo]      if @prato.update_attributes(:ativo => params[:ativo])      else      end  end  end  flash[:notice] = "fds"  redirect_to "/pratos/new?"  end  

View:

<%= check_box_tag 'Ativo', prato.id , prato.ativo,:class => "task-check2", :id=>"task-check2"  %>  <%= check_box_tag 'Sugestão', prato.id , prato.sugestao,:class => "task-check3", :id => "task-check3"  %>  

Javascript

$(".task-check2").bind('change', function(){        $.ajax({        url: '/pratos/'+this.value+'/toggle',        type: 'POST',        data: {"ativo": this.checked}      });      });      $(".task-check3").bind('change', function(){        $.ajax({        url: '/pratos/'+this.value+'/toggle',        type: 'POST',        data: {"sugestao": this.checked}      });      });  

Routes

resources :pratos do    member do      post 'toggle'    end  end  

Ok So everything works as intended... Problem is i want to show a message when user activates 3 checkboxes but Flash Notices and redirects aren't working... Can someone explain to me why?

Paperclip separate styles

Posted: 03 Jun 2016 06:56 AM PDT

How can i separate styles for different models?

I have my Photo model which generate my styles

large:'300x300#',huge:'800x800'

also i have two models witch use this styles

Product

and

Post

so i want to use

large style only for Product

and huge style only for Post

product => has_many :photos    post => has_one :photo    photo => belongs_to :post        belongs_to :product  has_attached_file :image, :styles => {large:'300x300#',huge:'800x800'}  

Is it possible?

Rails: Provide default value for the disabled select helper

Posted: 03 Jun 2016 02:54 AM PDT

I have a select helper as seen below, I have disabled it and would like give "1" as default value, but couldnt find how?

<%= f.select :fuel_incl, [[t('shared.incl'),'1'],[t('shared.notInc'),'0']], {}, {class: "Select-control u-sizeFull fuel_incl", :disabled => true} %>  

It is disabled so it should select 1 as default.

EDIT

I see that it works from the console;

<select class="Select-control u-sizeFull fuel_incl" disabled="disabled" name="boat[fuel_incl]" id="boat_fuel_incl">  <option selected="selected" value="1">Included</option>  <option value="0">Not Included</option></select>  

but it does not send as params, when I take out disable true and select value send the form, it works..

EDIT2

anyways, I have solved it by giving only one select value as;

<%= f.select :fuel_incl,                [[t('shared.incl'),'1']],                { selected: '1' },                { class: "Select-control u-sizeFull fuel_incl" } %>  

Rails, a way to render everything my app has in one json?

Posted: 03 Jun 2016 04:36 AM PDT

I want to render everything my app has to json, so I can pass it to android studio. I have a general controller and a method initialize and I want to pass everything from there.

class ApiController < ApplicationController      def initialize            @articles = Article.all          @areas = Area.all          @languages = Language.all          #now what?      end  end  

I know it's probably a starter's question but I can't find a simple example to see how this works. Or I'm not searching right. Do I need a gem, or I can do that with *render :json => @data * or something similar?

Thanks.

No comments:

Post a Comment