Monday, April 11, 2016

undefined method `errors' for nil:NilClass - Ruby on Rails | Fixed issues

undefined method `errors' for nil:NilClass - Ruby on Rails | Fixed issues


undefined method `errors' for nil:NilClass - Ruby on Rails

Posted: 11 Apr 2016 07:13 AM PDT

I am totally new in the Ruby on Rails. I have tried to show an message while register. Please check my controller and view code -

users_controller.rb

class UsersController < ApplicationController    #before_action :set_user, only: [:show, :edit, :update, :destroy, :success]      def login      render layout: false    end    def register      render layout: false      @user = User.new    end      def create_register      @user = User.new(create_user_params)      #raise @user.inspect      respond_to do |format|        if @user.save          format.html { redirect_to @users, notice: 'Registration was successfully created.' }          format.json { render :success, status: :created, location: @users }        else          format.html { render :register }          format.json { render json: @ruby_win_source.errors, status: :unprocessable_entity }        end      end    end      def success      raise @user.inspect    end        private    # Use callbacks to share common setup or constraints between actions.    def set_user      @user = User.find(params[:id])    end      # Never trust parameters from the scary internet, only allow the white list through.    def user_params      params.require(:user).permit(:name, :username, :email, :password, :image, :dob, :photo, :address)    end  end  

register.html.erb

<%= form_tag(@user) do |f| %>           <% if @user.errors.any? %>            <div id="error_explanation">              <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>              <ul>                <% @user.errors.full_messages.each do |message| %>                  <li><%= message %></li>                <% end %>              </ul>            </div>  <% end %>  

routes.rb

get    'register'   => 'users#register'  post   'register'   => 'users#create_register'  

URL - http://localhost:3000/register

While I am loading this page I got this error message -

enter image description here

I searched in google and getting some same issue link. Follow step but my problem still not resolved. Please help me :(

Rails 4: EOFError: end of file reached following any email in DEVELOPMENT only

Posted: 11 Apr 2016 07:13 AM PDT

I have rails app which uses devise ofr authentication and sidekiq for background email jobs. All of a sudden, in development only, I am getting the following error associated with an attempt to send an email from the app (e.g. devise forgotten password)

     EOFError: end of file reached  

Strangely the app in production works (heroku set up using sendgrid). I haven't changed any of my development email settings....

  ActionMailer::Base.default :from => 'slfwalsh@gmail.com'        config.action_mailer.delivery_method = :smtp      config.action_mailer.perform_deliveries = true      config.action_mailer.raise_delivery_errors = true      config.action_mailer.smtp_settings = {        :address => "smtp.gmail.com",        :port => 587,        :domain => '@gmail.com',        :user_name => "xxxxx@gmail.com",        :password => "xxxxxxxx",        :authentication => 'plain',        :enable_starttls_auto => true     }        config.action_mailer.default_url_options = { :host => 'localhost:3000' }  

I can't find anything to address this online. Also I note that ALL my apps in development, using similar settings are throwing the same error. I tried a different email address and password (again gmail) and no luck....

Don't Duplicate Entries Rails

Posted: 11 Apr 2016 07:04 AM PDT

I'm currently calling this every 3hrs, but it's storing duplicates of the same data. I've tried a few methods here on Stackoverflow but none of them seem to be actually working.

  def fetch_data        response = self.class.get("/tap-2_JD7rkZupwNmg91im5G/last_ready_run/data?format=json")      @elements = response.parsed_response["link"]        # To access the image src's:      image_srcs = @elements.collect { |e| e['image'] }        image_srcs.each do |image|        self.entries.create(image: image)      end    end  

Is there a way to check against each 'image' string that it collects and make sure it's not a duplicate before it inserts a new entry into the database

Thanks

conditional scope based on either two fields being true but not both

Posted: 11 Apr 2016 06:57 AM PDT

I am needing to create a scope that checks for either two fields on the model being true, however it shouldn't include records where both are true, only ones where either of them are. I hope that makes sense.

I am using Rails 3.2 and Mongo 3. Can any recommend a way to achieve this?

My first attempt has been

scope :with_training_complete, where(  :volunteer_training_completed => true  ).or(:face_to_face_training_attended => true)  

but that brings back only records where both are true.

any help would be much appreciated.

Rspec - user_path(user) is missing required keys: [:id]

Posted: 11 Apr 2016 06:48 AM PDT

In the browser everything works fine, but the Rspec test fail with this message:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"users", :id=>nil, :locale=>#<User id: 1, email: [...] } missing required keys: [:id]

My failing test:

subject {create(:client)} #from factory_girl    visit user_path(subject)  

For the test to pass, I have to explicitly write the id: visit user_path(id: subject)

The strange thing is that it was going fine before, until I ran a bundle update for railties etc. This problem has appeared for my other models as well (Profile, Job, etc).

I failed at finding a solution, any help would be very appreciated.

Rails Template is missing render json

Posted: 11 Apr 2016 06:45 AM PDT

actually i use rails for my REST API, and i need transform my object to json but when i try i got this error:

            <h1>Template is missing</h1>          <p>Missing template firms/show, application/show with {:locale=&gt;[:en], :formats=&gt;[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=&gt;[:erb, :builder, :arb, :jbuilder]}. Searched in:    * &quot;/Users/allan/Desktop/Work/back/app/views&quot;    * &quot;/Library/Ruby/Gems/2.0.0/gems/activeadmin-0.6.0/app/views&quot;    * &quot;/Library/Ruby/Gems/2.0.0/gems/kaminari-0.16.3/app/views&quot;    * &quot;/Library/Ruby/Gems/2.0.0/gems/devise_invitable-1.5.5/app/views&quot;    * &quot;/Library/Ruby/Gems/2.0.0/gems/devise-3.5.4/app/views&quot;  </p>  

This is my code

 def show          firm= Firm.find_by_subdomain(params[:subdomain])          if firm.present?            respond_to do |format|              @firm = firm              format.json { render :json => @firm.to_json }            end          end        end  

I hope someone here can help me :)

Rails: ActionController::ParameterMissing

Posted: 11 Apr 2016 06:49 AM PDT

I'm building an app that lets :users place :orders at :places. I am defining orders_params in PlacesController, but Rails says ParameterMissing ("params is missing or the value is empty: order")

How can I fix this, so that one can create an :order for :place_id through app/place/PLACE_ID/book ?

PlacesController:

def book      @place = Place.find(params[:id])      @order = Order.new(order_params)      if @order.save          flash[:success] = "Success"          redirect_to @place      else          render 'book'      end  end    private    def place_params    params.require(:place).permit(:place_name)  end    def order_params    params.require(:order).permit(:place_id, :user_id)  end  

Routes.rb

get 'book' => 'places#show#book'  get '/places/:id/book' => 'places#book', as: :place_book  resources :places  

OrdersController

class OrdersController < ApplicationController    def new  end    def create       @place = Place.find(@order.place_id)      @order = Order.new(user_id: current_user.id, place_id: @place)      if @order.save          flash[:success] = "Order placed"          redirect_to @place      else          render 'book'      end  end    def show  end    def edit   end    def update  end    def destroy  end    private    def order_params      params.require(:order).permit(:place_id, :user_id)  end  

end

Model: Order.rb

belongs_to :user  has_one :place  validates :user_id, presence: true  validates :place_id, presence: true  ## OTHER VALIDATIONS  

View: app/views/places/book

<%= form_for(@order) do |f| %>      <!-- SOME FORM_FORS -->      <%= f.submit "Place order", class: "btn btn-primary" %>  <% end %>  

Use ransack to find objects whose array attribute contain a specific string

Posted: 11 Apr 2016 06:25 AM PDT

Model A has attribute "languages", which is an array contains element such as "English", "French". My site has a form which allows user to select a language and it will display all object whose "languages" includes that language.

How to design my controller and view to do that? From the docs, there are ways to check if an element is in a query array, not the other way round.

this.setState not re-rendering view ReactJS and Ruby on Rails

Posted: 11 Apr 2016 06:25 AM PDT

I have a rails app with two reactJS components (not parent/child) that are currently communicating through a global events Pub/Sub system.

However when I run this.setState({ items: this.props.items }) I am getting the message Cannot read property 'items' of undefined.

Any help people can offer on why I might be getting this error would be much appreciated.

The basic setup I have is:

BasketContainer - subscribed to two events

class BasketContainer extends React.Component{    constructor() {      super()      this.state = {          items: [],          subTotal: 0,          totalPrice: 0,          deliveryPrice: 0      }  }  componentWillMount() {      this.setState( {          items: this.props.items,      })  }  componentDidMount() {      this.token = PubSub.subscribe('ADD_BASKET', this.handleUpdate)      this.token = PubSub.subscribe('REMOVE_ITEM', this.handleUpdate)      this.calculateTotals();  }    componentWillUnmount() {  PubSub.unsubscribe(this.token)  }    handleUpdate(msg, data){      console.log(msg)      this.setState({          items:this.props.items // ERROR MESSAGE - Cannot read property 'items' of undefined      })  }  .... Rest of file  

ProductItem - Add to Basket Event Publisher

class ProductItem extends React.Component{    constructor() {      super()        this.state = {           name: '',          price: 0,          code: '',          id: ''      }  }    componentWillMount() {      this.setState({          name: this.props.data.name,          price: this.props.data.price,          code: this.props.data.code,          id: this.props.data.id      })  }    addtoBasket() {      $.ajax({          type: "POST",          url: "/items",          dataType: "json",          data: {              item: {                  name: this.state.name,                  price: this.state.price,                  code: this.state.code              }          },          success: function(data) {              PubSub.publish('ADD_BASKET', data); // THIS WORKS FINE              console.log("success");          },          error: function () {              console.log("error");          }      })  }    render(){      let productName = this.props.data.name      let productPrice = this.props.data.price      let productCode = this.props.data.code      let productImg = this.props.data.image_url        return (          <div className="col-xs-12 col-sm-4 product">              <img src={productImg}/>              <h3 className="text-center">{productName}</h3>              <h5 className="text-center">£{productPrice}</h5>              <div className="text-center">                  <button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>              </div>          </div>      )  }  }  

BasketItem - Remove from Basket Publisher

class BasketItem extends React.Component{    constructor(props) {      super()        this.state = {           name: '',          price: 0,          code: '',          id: '',          quantity: 1,      }  }    componentWillMount() {      this.setState({          name: this.props.data.name,          price: this.props.data.price,          code: this.props.data.code,          id: this.props.data.id,      })  }    deleteItem() {      let finalUrl = '/items/' + this.state.id;      $.ajax({          type: "DELETE",          url: finalUrl,          dataType: "json",          success: function(data) {              PubSub.publish('REMOVE_ITEM', data); // THIS WORKS FINE          },          error: function () {              console.log("error");          }      })  }       render(){      let itemName = this.props.data.name      let itemCode = this.props.data.code      let itemQuantity = 1      let itemPrice = (this.props.data.price * itemQuantity).toFixed(2)      const itemId = this.props.data.id        return(          <tr>              <td>{itemName}</td>              <td>{itemCode}</td>              <td>{itemQuantity}</td>              <td><button className="btn btn-warning" onClick={this.deleteItem.bind(this)}>Remove</button></td>              <td>£{itemPrice}</td>          </tr>      )  }  }  

Setting state PubSub ReactJS and Rails

Posted: 11 Apr 2016 06:18 AM PDT

I have setup a PubSub events system but for some reason am receiving a Cannot read property 'items' of undefined when trying to set the state of my component again having successfully received.

It seems I don't have access to this but am unsure why?

BasketContainer Component

class BasketContainer extends React.Component{    constructor() {      super()      this.state = {          items: [],          subTotal: 0,          totalPrice: 0,          deliveryPrice: 0      }  }    componentWillMount() {      this.setState( {          items: this.props.items,      })  }    componentDidMount() {      this.token = PubSub.subscribe('ADD_BASKET', this.subscriber)      this.calculateTotals();  }    componentWillUnmount() {  PubSub.unsubscribe(this.token)  }    subscriber(msg, data){  console.log(msg, data) // CONSOLE LOGS CORRECTLY :)  this.setState({      items: this.props.items // RETURNING Cannot read property 'items' of undefined  })  }  .... bottom of file and Render ....  

ProductItem Component - where publish is executed

class ProductItem extends React.Component{    constructor() {      super()        this.state = {           name: '',          price: 0,          code: '',          id: ''      }  }    componentWillMount() {      this.setState({          name: this.props.data.name,          price: this.props.data.price,          code: this.props.data.code,          id: this.props.data.id      })  }    addtoBasket() {      $.ajax({          type: "POST",          url: "/items",          dataType: "json",          data: {              item: {                  name: this.state.name,                  price: this.state.price,                  code: this.state.code              }          },          success: function(data) {              PubSub.publish('ADD_BASKET', data); // THIS WORKS CORRECTLY              console.log("success");          },          error: function () {              console.log("error");          }      })  }    render(){      let productName = this.props.data.name      let productPrice = this.props.data.price      let productCode = this.props.data.code      let productImg = this.props.data.image_url        return (          <div className="col-xs-12 col-sm-4 product">              <img src={productImg}/>              <h3 className="text-center">{productName}</h3>              <h5 className="text-center">£{productPrice}</h5>              <div className="text-center">                  <button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>              </div>          </div>      )  }  

}

Any idea why I might be getting Cannot read property 'items' of undefined?

Rails - Unable to access parameters in controller

Posted: 11 Apr 2016 06:05 AM PDT

I have a Restaurant, Cart, and a User model. I would like to be redirected to a Cart form when entering a restaurant. This form will ask me for a table number and, thereafter, create a cart for the current user. However, when submitting the form I get a problem with the passed parameters

Couldn't find Restaurant with 'id'=  

I suppose they are not in the white list but I cannot find how to allow them... I will be thankful for any suggestions!

The passed params:

{"utf8"=>"✓",  "authenticity_token"=>"*****",   "cart"=>{"restaurant_id"=>"1",   "table_id"=>"4"},   "commit"=>"Create Cart",   "user_id"=>"1"}  

I am passing the restaurant_id with a hidden field and the table with an input

<%= f.hidden_field :restaurant_id, value: params[:restaurant_id] %>  <%= f.input :table_id %>  

In the cart controller:

    def create          @restaurant = Restaurant.find(params[:restaurant_id])          @table = @restaurant.tables.find(params[:table_id])          @cart = current_user.carts.new(cart_params)      ...      end  ....      def cart_params        params.require(:cart).permit(:restaurant_id, :table_id)      end  

$("form").submit(function() { Not working in Firefox

Posted: 11 Apr 2016 06:36 AM PDT

    $("form").submit(function() {          if ($("#content") != null) {              $("#content").replaceWith('<div id="page-loader" class="fade in"><span class="spinner"></span><span class="spinner-text center">We are running as fast as our little ninja feet can go...</span></div>');          }          return true;      });  

The above works fine on Chrome but does not work on Firefox. Not sure why but in Firefox the form is not actually submitted. The div replace works but no love on the submit, the page just stays idle.

The intent here is to capture a submit of any form and throw a spinner (CSS not an image) onto the page until the post / put is returned and the spinner is wiped out by the actual content div on the page reload (non ajax).

Before:

Before

After:

After

Code Removed (the post now appears):

Code Removed

<form accept-charset="UTF-8" action="/users/sign_in" class="new_user" id="new_user" method="post" role="form">  
            <!-- begin row -->              <div class="row">                  <!-- begin col-12 -->                  <div class="col-lg-6">                      <div class="form-group"><label class="sr-only control-label" for="user_email">Email</label><input autofocus="autofocus" class="form-control" id="user_email" name="user[email]" placeholder="E-mail" type="email" value="" /></div>                  </div>                  <div class="col-lg-6">                      <div class="form-group"><label class="sr-only control-label" for="user_password">Password</label><input class="form-control" id="user_password" name="user[password]" placeholder="Password" type="password" /></div>                  </div>              </div>              <!-- end row -->              <!-- begin row -->              <div class="row">                  <!-- begin col-12 -->                  <div class="col-md-12 center">                      </br>                  </div>              </div>              <!-- end row -->              <!-- begin row -->              <div class="row">                  <!-- begin col-12 -->                  <div class="col-md-12 center">                      <input class="btn" name="commit" type="submit" value="Sign in" />                      <div class="m-t-20">    <a href="/users/password/new">Forgot your password?</a><br/>    <a href="/users/confirmation/new">Didn&#39;t receive confirmation instructions?</a><br/>    <a href="/users/unlock/new">Didn&#39;t receive unlock instructions?</a><br/>                        </div>                  </div>              </div>              <!-- end row -->  

<script>  $(document).ready(function () {      App.init();        $("form").submit(function(){          if ($("#content") != null) {              $("#content").replaceWith('<div id="page-loader" class="fade in"><span class="spinner"></span><span class="spinner-text center">We are running as fast as our little ninja feet can go...</span></div>');          }          return true;          alert("Submitted");      });  });    $(function () {      var hash = window.location.hash;      hash && $('ul.nav a[href="' + hash + '"]').tab('show');  });  

UPDATE:

Ok so i am an idiot but for some reason this didn't cross my mind. What is happening is that the #content div includes the form i am replacing. So the mystery to me is why that worked in Chrome / IE and not in Firefox?

If i use the following it works but i get some dangling form elements:

$("form").submit(function(){          if ($("#content") != null) {              $("#content").append('<div id="page-loader" class="fade in"><span class="spinner"></span><span class="spinner-text center">We are running as fast as our little ninja feet can go...</span></div>');          }          return true;      });  

How do I create recurring events with simple form and Ruby? Is ice-cube the best gem for this?

Posted: 11 Apr 2016 05:30 AM PDT

I'm using Ruby on Rails to build an event booking site. At the moment the site only caters for one-off events on a particular date. I want to add the ability for somebody to create recurring events - weekly/monthly/bi-monthly etc. What is the best way to do this?

I'm using simple form gem, here's the code in the view -

<%= simple_form_for(@event) do |f| %>  <% if @event.errors.any? %>      <h2><%= pluralize(@event.errors.count, "error") %> prevented this     Event from saving:</h2>  <ul>      <% @event.errors.full_message.each do |message| %>      <li><%= message %></li>      <% end %>  </ul>    <%= f.collection_select :category_id, Category.all, :id, :name, {prompt:     "Choose a category"} %>  <!-- The above code loop assigns a category_id to each event -->    <%= f.input :image, as: :file, label: 'Image' %>  <%= f.input :title, label: 'Event Title' %>  <label>Location</label><%= f.text_field :location, id: 'geocomplete' %></br>  <label>Date</label><%= f.text_field :date, label: 'Date', id: 'datepicker' %>  <%= f.input :time, label: 'Time' %>  <%= f.input :description, label: 'Description' %>  <label>Number of spaces available</label><%= f.text_field :number_of_spaces,     label: 'Number of spaces' %>  <%= f.input :is_free, label: 'Tick box if Event is free of charge' %>  <%= f.input :price, label: 'Cost per person (leave blank if free of charge)'    %>  <%= f.input :organised_by, label: 'Organised by' %>  <%= f.input :organiser_description, label: 'Organiser description' %>  <%= f.input :url, label: "Link to Organiser site" %>    <%= f.button :submit, label: 'Submit' %>  

Handlebars template - compile on server side Rails

Posted: 11 Apr 2016 06:13 AM PDT

Is there a way to render Yfndlebars template on server side with Rails?

For example, this template nice rendered in client-side:

<td>    {{dish_name}}  </td>  <td>    {{dish_cost}}  </td>    {{restaurant_shop_name}}  {{#if user_has_rights}}    <td>      {{{dish_discounts}}}    </td>  {{/if}}  

but also i need to render it with ruby on rails, on server side. How can i do that?

update attributes working even if it is nil

Posted: 11 Apr 2016 06:22 AM PDT

I have a reset password page in which user has to fill password and password confirmation but even if he not fills and click on submit it he is redirect to the page .Also my 2nd error is if the user fills only confirm password and skip the password field still he is redirected to the page .I don't understand why @user.update_attributes not working properly.
[user.rb]

class User < ActiveRecord::Base      validates_presence_of :password  end  


[users_controller]

def change_password          @user = User.find_by(reset_password_token: params[:users_reset_password_path][:token])            if @user.update_attributes(:name => @user.name,:email => @user.email,:status => @user.status, :password => params[:users_reset_password_path][:password],:password_confirmation => params[:users_reset_password_path][:password_confirmation])          flash[:notice] = "password successfully updated"        redirect_to users_path      else        @token = @user.reset_password_token         render  users_reset_password_path      end  end  


[users/_reset_password.html.erb]

    <div id="nav-col-submenu"></div>        </div>            <div id="content-wrapper">        <div class="row">      <div class="col-lg-12">          <div class=" clearfix">                  <div id="login-box">            <%= render :partial => "shared/error_messages", :locals => { :errors => @user.errors } %>            <div id="login-box-holder">                <div class="row">                <div class="col-xs-12">                  <header id="login-header">                    <div id="login-logo">                      <img src="/assets/gionee_logo1.png" alt=""/>                    </div>                  </header>            <div id="login-box-inner">          <%= form_for :users_reset_password_path  do |f| %>                        <div class="input-group">                        <span class="input-group-addon"><i class="fa fa-user"></i></span>            <%= f.password_field :password,class: "form-control",placeholder: "Password" %>                      </div>                      <div class="input-group">                        <span class="input-group-addon"><i class="fa fa-key"></i></span>            <%= f.password_field :password_confirmation,class: "form-control",placeholder: "Confirm Password" %>                      </div>               <%= f.hidden_field :token ,value: if params[:token] != nil then params[:token] else @token end%>                        <div class="row">                        <div class="col-xs-12">            <%= f.submit "Reset Password",class: "btn btn-success col-xs-12" %>                           </div>                      </div>                      <% end %>            </div>            </div>        </div>      </div>                </div>                    </div>              </div>            </div>            </div>      <%= render 'page_js/user_search'%>  

How to store and use algorithms?

Posted: 11 Apr 2016 06:29 AM PDT

  • I have a Rails app that displays transportation prices of companies (think e.g. momondo.com).
  • Those companies are 'created' using the same data model for all of them. Every company has its unique way to calculate a price.
  • I have to implement different algorithms for every single one. In some cases an 'algorithm' could just be a lookup in a table, in other cases it's a math formula.

    So, what kind of data model is the most appropriate here? Thanks in advance

Image not showing in view

Posted: 11 Apr 2016 05:13 AM PDT

I'm currently trying to iterate over my entries and display the image from each of them. The image url is stored as a string in the database.

<% @feed.entries.each do |image| %>    <div class="grid-item">      <%= image_tag(image) %>    </div>  <% end %>  

When using this, unfortunately this comes up within the image src

/images/#<Entry:0x007fcf40144210>  

Not too sure what this is doing.

EDIT

#<Entry id: 1, title: nil, image: "http://40.media.tumblr.com/889c65a662a1b690f299593...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 2, title: nil, image: "http://41.media.tumblr.com/3cfd8c9c93870fa716356bc...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 3, title: nil, image: "http://40.media.tumblr.com/7906907023dd04ff5c4be15...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 4, title: nil, image: "http://49.media.tumblr.com/3405440b713440ba490f473...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 5, title: nil, image: "http://45.media.tumblr.com/9185ff46269e01bd6d7827e...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 6, title: nil, image: "http://41.media.tumblr.com/e1d5e279df2b765c901c9fa...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 7, title: nil, image: "http://41.media.tumblr.com/061ab14be3316e82b1ea67e...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 8, title: nil, image: "http://41.media.tumblr.com/975c58b368d20d6f54f3eed...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 9, title: nil, image: "http://49.media.tumblr.com/65e811cefd6ec3235d933a0...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, #<Entry id: 10, title: nil, image: "http://41.media.tumblr.com/b2486d84cc2c30bbdb50b0b...", source: nil, created_at: "2016-04-11 11:31:00", updated_at: "2016-04-11 11:31:00", feed_id: 1>, ...]>  

Using Rails 5 (the API flag) and getting no route error despite route declared

Posted: 11 Apr 2016 05:09 AM PDT

This is my controller:

class Api::V1::UsersController < ApplicationController    respond_to :json      def show      respond_with User.find(params[:id])    end  end  

This is my routes.rb

require 'api_constraints'    Rails.application.routes.draw do    devise_for :users    # Api definition    namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do      scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do        resources :users, :only => [:show]      end    end  end  

This is my lib/api_constraints.rb

class ApiConstraints    def initialize(options)      @version = options[:version]      @default = options[:default]    end      def matches?(req)      @default || req.headers['Accept'].include?("application/vnd.myapp.v#{@version}")    end  end  

I added a record to my DB as can be seen here:

[3] pry(main)> User.all    User Load (0.4ms)  SELECT "users".* FROM "users"  => [#<User:0x007fbdb31079f8    id: 1,    email: "abc@test.com",    encrypted_password: "$2a$11$rvOrK1bmuuNwwc78ERxG3eCrKiUu9NTZsJ/nmirqb.3yRBHYUK69S",    reset_password_token: nil,    reset_password_sent_at: nil,    remember_created_at: nil,    sign_in_count: 0,    current_sign_in_at: nil,    last_sign_in_at: nil,    current_sign_in_ip: nil,    last_sign_in_ip: nil,    created_at: Mon, 11 Apr 2016 10:35:39 UTC +00:00,    updated_at: Mon, 11 Apr 2016 10:35:39 UTC +00:00>]  

Yet this is the error I get in my rails console:

ActionController::RoutingError (No route matches [GET] "/users/1"):    actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'  web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app'  web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call'  web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch'  web-console (3.1.1) lib/web_console/middleware.rb:18:in `call'  actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'  railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app'  railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call'  activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged'  activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged'  railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call'  actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call'  rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call'  activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call'  actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call'  rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call'  railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call'  puma (3.2.0) lib/puma/configuration.rb:227:in `call'  puma (3.2.0) lib/puma/server.rb:561:in `handle_request'  puma (3.2.0) lib/puma/server.rb:406:in `process_client'  puma (3.2.0) lib/puma/server.rb:271:in `block in run'  puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'  

And this is what I see in my browser:

{"status":404,"error":"Not Found","exception":"#\u003cActionController::RoutingError: No route matches [GET] \"/users/1\"\u003e","traces":{"Application Trace":[],"Framework Trace":[{"id":0,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'"},{"id":1,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app'"},{"id":2,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call'"},{"id":3,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch'"},{"id":4,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `call'"},{"id":5,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'"},{"id":6,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app'"},{"id":7,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call'"},{"id":8,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged'"},{"id":9,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged'"},{"id":10,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged'"},{"id":11,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call'"},{"id":12,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call'"},{"id":13,"trace":"rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call'"},{"id":14,"trace":"activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'"},{"id":15,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call'"},{"id":16,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call'"},{"id":17,"trace":"rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call'"},{"id":18,"trace":"railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call'"},{"id":19,"trace":"puma (3.2.0) lib/puma/configuration.rb:227:in `call'"},{"id":20,"trace":"puma (3.2.0) lib/puma/server.rb:561:in `handle_request'"},{"id":21,"trace":"puma (3.2.0) lib/puma/server.rb:406:in `process_client'"},{"id":22,"trace":"puma (3.2.0) lib/puma/server.rb:271:in `block in run'"},{"id":23,"trace":"puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'"}],"Full Trace":[{"id":0,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'"},{"id":1,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app'"},{"id":2,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call'"},{"id":3,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch'"},{"id":4,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `call'"},{"id":5,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'"},{"id":6,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app'"},{"id":7,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call'"},{"id":8,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged'"},{"id":9,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged'"},{"id":10,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged'"},{"id":11,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call'"},{"id":12,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call'"},{"id":13,"trace":"rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call'"},{"id":14,"trace":"activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'"},{"id":15,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call'"},{"id":16,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call'"},{"id":17,"trace":"rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call'"},{"id":18,"trace":"railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call'"},{"id":19,"trace":"puma (3.2.0) lib/puma/configuration.rb:227:in `call'"},{"id":20,"trace":"puma (3.2.0) lib/puma/server.rb:561:in `handle_request'"},{"id":21,"trace":"puma (3.2.0) lib/puma/server.rb:406:in `process_client'"},{"id":22,"trace":"puma (3.2.0) lib/puma/server.rb:271:in `block in run'"},{"id":23,"trace":"puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'"}]}}  

Edit 1

This is my rake routes

$ rake routes  [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.  [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.  [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.                    Prefix Verb   URI Pattern                    Controller#Action          new_user_session GET    /users/sign_in(.:format)       devise/sessions#new              user_session POST   /users/sign_in(.:format)       devise/sessions#create      destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy             user_password POST   /users/password(.:format)      devise/passwords#create         new_user_password GET    /users/password/new(.:format)  devise/passwords#new        edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit                           PATCH  /users/password(.:format)      devise/passwords#update                           PUT    /users/password(.:format)      devise/passwords#update  cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel         user_registration POST   /users(.:format)               devise/registrations#create     new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new    edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit                           PATCH  /users(.:format)               devise/registrations#update                           PUT    /users(.:format)               devise/registrations#update                           DELETE /users(.:format)               devise/registrations#destroy                  api_user GET    /users/:id(.:format)           api/v1/users#show {:format=>:json, :subdomain=>"api"}  

Edit 2

This is my application controller:

class ApplicationController < ActionController::API  end  

Edit 3

This is my users_controller_spec.rb test that actually passes:

require 'rails_helper'    describe Api::V1::UsersController do    before(:each) { request.headers['Accept'] = "application/vnd.myapp.v1" }      describe "GET #show" do      before(:each) do        @user = FactoryGirl.create :user        get :show, id: @user.id, format: :json      end        it "returns the information about a user on a hash" do        user_response = JSON.parse(response.body, symbolize_names: true)        expect(user_response[:email]).to eql @user.email      end        it { should respond_with 200 }    end    end  

This is the result:

$ rspec spec/controllers  DEPRECATION WARNING: use_transactional_fixtures= is deprecated and will be removed from Rails 5.1 (use use_transactional_tests= instead). (called from <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:3)  DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only  keyword arguments in future Rails versions.    Examples:    get :show, params: { id: 1 }, session: { user_id: 1 }  process :update, method: :post, params: { id: 1 }   (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9)  DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only  keyword arguments in future Rails versions.    Examples:    get :show, params: { id: 1 }, session: { user_id: 1 }  process :update, method: :post, params: { id: 1 }   (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9)  .DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only  keyword arguments in future Rails versions.    Examples:    get :show, params: { id: 1 }, session: { user_id: 1 }  process :update, method: :post, params: { id: 1 }   (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9)  DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only  keyword arguments in future Rails versions.    Examples:    get :show, params: { id: 1 }, session: { user_id: 1 }  process :update, method: :post, params: { id: 1 }   (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9)  .    Finished in 0.41411 seconds (files took 3.33 seconds to load)  2 examples, 0 failures  

TypeError: children[x].firstChild is null

Posted: 11 Apr 2016 05:02 AM PDT

Converting prototype into jQuery -

Getting error

TypeError: children[x].firstChild is null

How to convert firstChild into jQuery

this.drawNumbers = function() {  var children = this.getVisibleUsedElements();    for(var x=0;x<children.length;x++) {    children[x].firstChild.firstChild.firstChild.firstChild.innerHTML = String(x + 1);    }  };  

calculate score if something true

Posted: 11 Apr 2016 04:34 AM PDT

I have an application where i take in some data from a user, everything is working fine. I am trying to build a score in the model where if some data is present the score goes up, and i am trying something like this:

def score   score = 0   if self.moving = true     score += 5   end  end  

Here is my form and the 'moving' column is a boolean:

<div class="field">    <%= f.select :moving, [['Yes', true], ['No',false]], {}, :class => 'form-control' %>  </div>  

What happens is when I try this, when it is true 'yes' the score has 5 added but if i change it to false, I would like the score to go back down to the original score which has been built.

Also the score should be stored in a column which has been created in the database, i tried using self.score but it does not seem to work?

thanks for the help in advance.

Access Doorkeeper from action Rails Controller

Posted: 11 Apr 2016 04:52 AM PDT

Is there any chance to access authenticate Doorkeeper method from a rails action controller? I would like to skip authentication just for one of my actions('show') but if a specific condition aapplies I want to call the apiauthenticate method to do its job. So in the action 'show', first of all I check a condition, and if does not apply, then I need to activate the api_authenticate. I'm launching a test that should call api_authenticate and stop it there. But for some reason it keeps going on and it does not stop.

This is the code of my controller

skip_before_action :api_authenticate, only: :show    def show    param! :id, String, required: true      post = Services::Posts.find(params[:id])      if  post.public      @post = post      @user_id = nil    else      api_authenticate       ap "it shouldnt get here if user is not logged in"      user = current_resource_owner      @post = Services::Posts.show(params[:id], user)      @user_id = user.identity rescue nil    end  end    #more actions....  

And this is the api_controller.rb where I have the authenticate method

class ApiController < ApplicationController    protect_from_forgery with: :null_session      # Check the user is authenticated    before_action :api_authenticate      rescue_from ActionController::RoutingError, :with => :route_error    rescue_from ::AbstractController::ActionNotFound, :with => :action_error    rescue_from Exception, :with => :base_error if Rails.env.production?      def api_authenticate      doorkeeper_authorize!()    end  end  

Show time instead of value in chartkick column_chart

Posted: 11 Apr 2016 04:57 AM PDT

In context of the snippet below is it possible to calculate the chart based on the values but write a custom function that changes these values to a string representation? For example, if i want to change value from seconds into a formatted time string like this: "00:01:11" would be shown instead of the value 71.

data = {"Training" => 1}, "Game" => 2}  column_chart [{name: "Goals", data: data}]  

"Training" would be "00:00:01" and "Game" would be "00:00:02" and the y axis would have changed according to this as well.

If it is hard or not possible how else would you recommend doing this?

Update two components no relationship Ruby on Rails & ReactJS

Posted: 11 Apr 2016 05:01 AM PDT

I have a working app using Ruby on Rails and ReactJS which has four components:

  1. ProductContainer
  2. ProductItem (child of ProductContainer)
  3. BasketContainer
  4. BasketItem (child of BasketContainer)

At the moment I use Ajax calls to create new Basket Items when a 'Add to Basket' button is clicked in my Product Items Component. This works fine but the state is not updating without a page refresh and I am unsure how to alert BasketContainer/BasketItem that it needs to re-render the component.

I believe I need to setState on the success of my Ajax call but am unsure how to do this for another component. Any advice would be much appreciated.

ProductItem Component

class ProductItem extends React.Component{    constructor() {      super()        this.state = {           name: '',          price: 0,          code: '',          id: ''      }  }    componentWillMount() {      this.setState({          name: this.props.data.name,          price: this.props.data.price,          code: this.props.data.code,          id: this.props.data.id      })  }    addtoBasket() {      $.ajax({          type: "POST",          url: "/items",          dataType: "json",          data: {              item: {                  name: this.state.name,                  price: this.state.price,                  code: this.state.code              }          },          success: function() {              console.log("success");          },          error: function () {              console.log("error");          }      })  }    render(){      let productName = this.props.data.name      let productPrice = this.props.data.price      let productCode = this.props.data.code      let productImg = this.props.data.image_url        return (          <div className="col-xs-12 col-sm-4 product">              <img src={productImg}/>              <h3 className="text-center">{productName}</h3>              <h5 className="text-center">£{productPrice}</h5>              <div className="text-center">                  <button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>              </div>          </div>      )  }  

}

BasketItem Component

class BasketItem extends React.Component{    constructor(props) {      super()        this.state = {           name: '',          price: 0,          code: '',          id: '',          quantity: 1,      }  }    componentWillMount() {      this.setState({          name: this.props.data.name,          price: this.props.data.price,          code: this.props.data.code,          id: this.props.data.id,      })  }    deleteItem() {      let finalUrl = '/items/' + this.state.id;      $.ajax({          type: "DELETE",          url: finalUrl,          dataType: "json",          success: function(response) {              console.log("successfully deleted");          },          error: function () {              console.log("error");          }      })  }         render(){      let itemName = this.props.data.name      let itemCode = this.props.data.code      let itemQuantity = 1      let itemPrice = (this.props.data.price * itemQuantity).toFixed(2)      const itemId = this.props.data.id        return(          <tr>              <td>{itemName}</td>              <td>{itemCode}</td>              <td>{itemQuantity}</td>              <td><button className="btn btn-warning" onClick={this.deleteItem.bind(this)}>Remove</button></td>              <td>£{itemPrice}</td>          </tr>      )  }  

}

ProductContainer Component

class ProductContainer extends React.Component {    constructor() {      super()      this.state = {          products: []      }  }    componentWillMount() {      this.setState( {          products: this.props.products      })  }    render(){      let p = this.state.products        return(          <div>              <h1>Products</h1>              <div className="row">                  {p.map(function(product){                      return <ProductItem data={product} key={product.id} />;                  })}              </div>          </div>      )  }  

}

BasketContainer Component

class BasketContainer extends React.Component{    constructor() {      super()      this.state = {          items: [],          subTotal: 0,          totalPrice: 0,          deliveryPrice: 0      }  }    componentWillMount() {      this.setState( {          items: this.props.items,      })  }    componentDidMount() {      this.calculateTotals();  }    calculateTotals() {      let subtotal = this.state.subTotal      let delivery = this.state.deliveryPrice        for (var i=0; i<this.state.items.length; i++) {          subtotal += Number(this.state.items[i].price);      }        if (subtotal > 90) {          delivery = 0;      } else if (subtotal >= 50 & subtotal < 90 ) {          delivery = 2.95;      } else {          delivery = 4.95;      }        this.setState( {          deliveryPrice: delivery,          subTotal: subtotal,          totalPrice: subtotal + delivery      })  }    render(){        const {          totalPrice,          subTotal,          deliveryPrice      } = this.state;        let i = this.state.items      let basketBlock;      let basketCount;      let basketSubtotal;      let basketDelivery;      let basketTotal;        if (i) {            if (i.length === 1) {              basketCount = (                  <span className="basket-count">                      ({i.length} item)                  </span>              )          } else {              basketCount = (                  <span className="basket-count">                      ({i.length} items)                  </span>              )          }            basketSubtotal = (              <tr>                  <td></td>                  <td></td>                  <td></td>                  <th>Subtotal</th>                  <td>£{subTotal.toFixed(2)}</td>              </tr>          )          basketDelivery = (              <tr>                  <td></td>                  <td></td>                  <td></td>                  <th>Delivery</th>                  <td>£{deliveryPrice.toFixed(2)}</td>              </tr>          )          basketTotal = (              <tr>                  <td></td>                  <td></td>                  <td></td>                  <th>Total</th>                  <td>£{totalPrice.toFixed(2)}</td>              </tr>          )          basketBlock = (              <div className="col-xs-12">                  <div className="well">                      <table className="table table-responsive">                          <thead>                              <tr>                                  <th>Product</th>                                  <th>Code</th>                                  <th>Quantity</th>                                  <th>Actions</th>                                  <th>Price</th>                              </tr>                          </thead>                          <tbody>                              {i.map(function(item){                                  return <BasketItem data={item} key={item.id} />;                              })}                              {basketSubtotal}                              {basketDelivery}                              {basketTotal}                          </tbody>                      </table>                  </div>              </div>          )        } else {            basketCount = (              <span className="basket-count">                  pluralize(0 Items)              </span>          )          basketBlock = (              <div className="col-xs-12">                  <div className="well">                      <h5>Add an item</h5>                  </div>              </div>          )      }        return(          <div>              <h1>Basket {basketCount}</h1>              <div className="row">                  {basketBlock}              </div>          </div>      )  }  

}

Pages Index - where the components are mounted into the view

<div class="container-fluid">  <div class="row">      <div class="col-xs-12 col-sm-8">          <%= react_component('ProductContainer', render( template: 'products/index.json.jbuilder')) %>      </div>      <div class="col-xs-12 col-sm-4 basket">          <%= react_component 'BasketContainer', render( template: 'items/index.json.jbuilder') %>      </div>  </div>  

joins() and where() request on association with custom table name

Posted: 11 Apr 2016 06:28 AM PDT

I have two models

Album.rb

class Album < ActiveRecord::Base    has_many :tracks    self.table_name = 'prefix_album'  end  

Track.rb

class Track < ActiveRecord::Base    belongs_to :album    self.table_name = 'prefix_track'  end  

Now, because reasons, the table names are prefixed, so I have prefix_album and prefix_track tables in my database. For basic use, it works fine.

Now the problem with the following query :

Album.joins(:tracks).where(tracks: { id: [10, 15] })  

Results in the following SQL :

SELECT * FROM "prefix_albums" INNER JOIN "prefix_tracks" ON "prefix_tracks"."album_id" = "prefix_albums"."id" WHERE "tracks"."id" IN (10, 15)  

Which fails because WHERE "tracks"."id" should be WHERE "prefix_tracks"."id". Any idea why active_record is able to get the correct table name for .joins(:tracks) but not for .where(tracks: {}) ?

Anyway I have figured this workout : Album.joins(:tracks).merge(Track.where(id: [10,15])) which gives the same result and works.

But I would like to know why the former didn't work

is there a way to re-render?

Posted: 11 Apr 2016 05:17 AM PDT

I have written an API in which I am rescuing from all StandardError. Incase of any StandardError, I send an exception email and render json with error message.

This works great except when the exception is raised from views (i am using jbuilder for json responses). As then when I render json with error message, it raises double render exception cause render has already been called in controller.

Is there a way to override the initial render call?

ruby 2.1.8

rails 4.2.6

how to store json response to javascript variable and display

Posted: 11 Apr 2016 04:14 AM PDT

How to get json response in javascript variable?

This is my index.json.jbuilder file

`json.array! @properties do |p|    json.id p.id    json.Space_name p.Space_name    json.address p.address    json.city p.city    json.state p.state    json.country p.country    json.latitude p.latitude    json.longitude p.longitude  end`

Now i am getting the json response like this

   [{"id":22,"Space_name":"mumbai","address":"mumbai","city":"sharjah","state":"fujairah","country":"United Arab Emirates","latitude":"19.0759837","longitude":"72.87765590000004"},{"id":2,"Space_name":"Bangalore","address":"Banglore","city":"abu-dhabi","state":"ajman","country":"United Arab Emirates","latitude":"37.2809455","longitude":"49.59241339999994"}

but i need output like this(stored in one variable) ,for eg:

properties= [{"id":22,"Space_name":"mumbai","address":"mumbai","city":"sharjah","state":"fujairah","country":"United Arab Emirates","latitude":"19.0759837","longitude":"72.87765590000004"},{"id":2,"Space_name":"Bangalore","address":"Banglore","city":"abu-dhabi","state":"ajman","country":"United Arab Emirates","latitude":"37.2809455","longitude":"49.59241339999994"}

Here i am using jbuilder gem for json respose. Any help is appreciatable.

Self educating with outdated tutorials [on hold]

Posted: 11 Apr 2016 03:51 AM PDT

I've been self educating to learn programming, but it seems most tutorials are outdated and I spend a huge chunk of my study time getting stuck because some prefix has changed, or I realise the tutorial was written 4 years ago.

How would you direct a new student of programming to find efficient education?

Thanks, I'm getting burnt out.

How can a gem (unintentionally) change the migrations path?

Posted: 11 Apr 2016 03:46 AM PDT

I wrote a Gem (https://github.com/absolutedevops/civo) which is a simple Rails Engine containing a few API accessing models.

However, when I include it in a Rails project, any generators create their files under the Gem's source code not the project's. I can't see anything I'm doing in the Gem that would cause this. It's repeatable (it's happening in two projects at my company and I can reproduce it with a minimal set of steps below).

Can anyone tell me how I've managed this? I've been a Rails user for many years but haven't ever come across this before.

$ rails -v  Rails 4.2.6  $ rails new civo-test  [...]  Bundle complete! 12 Gemfile dependencies, 55 gems now installed.  Use `bundle show [gemname]` to see where a bundled gem is installed.           run  bundle exec spring binstub --all  * bin/rake: spring inserted  * bin/rails: spring inserted  $ cd civo-test  $ echo 'gem "civo"' >> Gemfile  $ bundle  [...]  Bundle complete! 13 Gemfile dependencies, 66 gems now installed.  Use `bundle show [gemname]` to see where a bundled gem is installed.  $ rails g migration a_new_migration_here  Running via Spring preloader in process 75091        invoke  active_record        create    db/migrate/20160411093346_a_new_migration_here.rb  $ ls -l db/migrate/20160411093346_a_new_migration_here.rb  ls: db/migrate/20160411093346_a_new_migration_here.rb: No such file or directory  $ rails g migration a_new_migration_here                   Running via Spring preloader in process 75193        invoke  active_record     identical    db/migrate/20160411093346_a_new_migration_here.rb  $ ls -l /Users/andy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/civo-0.3.21/db/migrate/   total 8  -rw-r--r--  1 andy  staff  73 11 Apr 10:33 20160411093346_a_new_migration_here.rb  

Gettext program

Posted: 11 Apr 2016 06:38 AM PDT

Given the phrase:

"You've successfully donated €10 to Doctors of the World"  

I wanted to dynamically generate this text for different amounts and charity names, which i did using

_("You've donated %{amount} to %{charity_name}")  

Where charity_name comes from a list of possible charities and each charity is a hash with data about the charity.

I'm not a french speaker and only learnt basic french in school but the problem with doing this (which is probably immediately obvious to any speaker of a language with gendered articles) is that the "to" part of the translation can take various forms a la, au, a'l or aux depending on the noun.

eg "Vous souhaitez donner 10€ aux Médecins du Monde"

What is the best way to handle this using gettext, given that this will need to be scaled to other languages? There are only a few cases where this will need to be done because most cases of dynamic text (99%+ can be handled fine with parameters.

I've thought of 3 ways to do this:

1) Have highly dynamical text such as this generated from a function, one per message per language as necessary. The function accepts an amount and charity name as a parameter and returns the translated text.

2) Manually add a translation for "to " for each charity and use that in place of %{charity_name} and then get the translation from the po file.

3) Add an entry in each charity hash specifying the form of the "to " eg the hash for les Médecins du Monde would also store aux Médecins du Monde.

Are any of these methods viable or is there a better alternative I'm not thinking off?

can any one tell me how to do this one n case/switch statement in rails

Posted: 11 Apr 2016 04:15 AM PDT

this data im getting from another table becauase i have 2 modes which is separately storing this id's to fetch that data only im doing like this
i need to write this below code in switch/case statement

@pfold=""       if(employeeproof.proof.id == 1 )         @pfold = employeeproof.proof_value    end    @pfnew=""        if(employeeproof.proof.id == 1 )       @pfold = employeeproof.proof_value      end   like this i have 20 conditions can any one tell me how to write this one in switch/case statement in rails  

1 comment: