Wednesday, October 19, 2016

adding a small API to a web application | Fixed issues

adding a small API to a web application | Fixed issues


adding a small API to a web application

Posted: 19 Oct 2016 08:12 AM PDT

I have a rails application with some standard routes, and I would like to add some API endpoints into it.

I figure I just have to add some routes (probably under a scope '/api'), create some new controllers that extend ActionController::API, and then perhaps do something so rails magically knows how to render the JSON data.

Are there any guides on how to do this? Everything I can find talks about creating 'API only' applications, but doesn't discuss adding a few API endpoints to an existing web application.

How do I use JSON with Sqlite on rails?

Posted: 19 Oct 2016 08:04 AM PDT

I am trying to get data from my sqlite database on rails using JSON but I dont know how to. I already did all the scaffolding. what gems do you recomend and how do I used them with an exiting project from sqlite database.

Next and previous link (item) in filtered Rails ActiveRecord by Filterrific gem

Posted: 19 Oct 2016 08:03 AM PDT

I need advise for my project. I have the filtered result ActiveRecord from Gem Filterrific and I need get link to next and previous item (object) in actual filtered Activerecord.

For example my ActiveRecord for @images

  #<ActiveRecord::Relation [#<Image id: 22787, position: 4240, long_name: "a4240_PERGOLY_OUTDOOR_LIVING_LUKAS_RACEK_PRIVATNI_...", description: "Barva bílá ALU RAL 9010 texturovaná, látka screen ...", manager_id: 6, category_id: 4, product_id: 15, company_id: 0, home_id: 5, created_at: "2016-10-08 11:20:24", updated_at: "2016-10-08 11:20:24", place_id: 2>,   #<Image id: 22788, position: 4260, long_name: "a4260_PERGOLY_OUTDOOR_LIVING_LUKAS_RACEK_PRIVATNI_...", description: "Barva bílá ALU RAL 9010 texturovaná, látka screen ...", manager_id: 6, category_id: 4, product_id: 15, company_id: 0, home_id: 5, created_at: "2016-10-08 11:20:24", updated_at: "2016-10-08 11:20:24", place_id: 2>,   #<Image id: 22789, position: 4280, long_name: "a4280_PERGOLY_OUTDOOR_LIVING_LUKAS_RACEK_PRIVATNI_...", description: "Barva bílá ALU RAL 9010 texturovaná, látka screen ...", manager_id: 6, category_id: 4, product_id: 15, company_id: 0, home_id: 5, created_at: "2016-10-08 11:20:26", updated_at: "2016-10-08 11:20:26", place_id: 2>,   #<Image id: 22790, position: 4300, long_name: "a4300_PERGOLY_OUTDOOR_LIVING_LUKAS_RACEK_PRIVATNI_...", description: "Barva bílá ALU RAL 9010 texturovaná, látka screen ...", manager_id: 6, category_id: 4, product_id: 15, company_id: 0, home_id: 5, created_at: "2016-10-08 11:20:27", updated_at: "2016-10-08 11:20:27", place_id: 2>]>  

And I need by using link_to get next and previous link in my view only at actual filtered result, not in whole Object Images.

I tried many many resources, but I can figure out.

Anybody please help me? Thank you very much for your time...

I use rails 5

error postgreSQL - ubuntu "rake db:migrate"

Posted: 19 Oct 2016 08:04 AM PDT

I'm a new rails.I tried to set up rake db:migrate db:seed and bundle exec db:migrate db seed but it's not working for me.Can u guys help me?please.

postgres@DungXinhDep:/home/ducdung/ruby-lab-2-hanoi-vinh$ rake db:migrate rake aborted! Errno::EACCES: Permission denied @ rb_sysopen - /home/ducdung/ruby-lab-2- hanoi-vinh/db/schema.rb /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:252:in initialize /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:252:in open /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:252:in block (3 levels) in <top (required)> /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:66:in block (2 levels) in <top (required)> /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:59:in block (2 levels) in <top (required)> /var/lib/gems/2.3.0/gems/rake-11.3.0/exe/rake:27:in' Tasks: TOP => db:schema:dump (See full trace by running task with --trace)

postgres@DungXinhDep:/home/ducdung/ruby-lab-2-hanoi-vinh$ bundle exec rake db:mmigrate /usr/lib/ruby/vendor_ruby/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /var/lib/gems/2.3.0 in PATH, mode 040777 rake aborted! Don't know how to build task 'db:mmigrate' (see --tasks) /var/lib/gems/2.3.0/gems/rake-11.3.0/exe/rake:27:in `' (See full trace by running task with --trace)

How to include a WebGL project in a Rails app

Posted: 19 Oct 2016 07:48 AM PDT

I've got a small Unity game, and I'm trying to export it using WebGL so it can be included in our Rails app... that said, I have no idea where to place the files or what to do with them so that they will be picked up properly. Through stabbing in the dark, I've been able to get the data/code/memUrl values to point at the files (or at least stop erroring at me), but I had to add 'gz' to the file extensions to get them picked up, so I don't know if that broke anything.

I'v put UnityLoader.js in public/javascripts,Release folder in public. I'm getting some JS errors like this: enter image description here

Does anyone have a line on a tutorial that walks through how to include WebGL output in a Rails app? Any help would be greatly appreciated.

SendGrid some images not showing up in HTML mail

Posted: 19 Oct 2016 07:40 AM PDT

Im using Sendgrid with Ruby on rails version 2.3.18 and tinymce editor to send campaign emails through my app.

When i try to send a campaign HTML email with multiple linked images inside it (stored on amazon), some of the images gets broken and not displayed. when checking the email in developer tools, i see that the broken images SRC is messed up. The weird thing is: 1. It happens even if i send an email with the same image multiple times. 2. I debugged my code to the last line of code before SendGrid takes over, and all of the images SRC are identical and works properly up to that point.

Here is the content of the campaign email before Sendgrid takes over, notice that the 7th img tag is identical to all of the other img tags:

http://pastebin.com/UxTUxxLY

and this is what renders in the email itself (dev tools on the mail), Notice how the 7th img tag SRC attribute is different than the rest, even though its the same image:

http://pastebin.com/EWB4a0tR

Iv tried different email supplier such as hotmail to see wheter its an issue with gmail specificly, and its not.

any idea what could be the source of the image breaking?

Nested form not properly generate

Posted: 19 Oct 2016 08:03 AM PDT

Attachment

Webpage   -> Sections (Has Many)      -> Header (Has One)         -> HeaderTabs (Has Many)  

I make nested form for above structure and it's display me properly, But When I'm adding new header_tabs on click of 'Add new Header Tab', It's add new fields but the indexing value is same as first one.

<div class="header_tabs_forms">      <div class="form-group">          <label class="control-label col-lg-3">&nbsp;</label>      <div class="col-lg-1">          <input type="hidden" value="false" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][_destroy]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0__destroy"><a class="btn btn-danger btn-xs rmhdrtab remove_nested_fields" data-association="header_tabs" href="javascript:void(0)"><i class="fa fa-close"></i></a>      </div>      <div class="col-lg-6 header_tabs">          <input placeholder="Write Tab Name" class="form-control form-ctr100 required" require="true" style="width:100%;" type="text" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][tab_name]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0_tab_name">          <div class="error"></div>      </div>      <div class="col-lg-2 header_tabs">          <input class="form-control form-ctr2 required" min="1" require="true" type="text" value="1" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][position]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0_position">      </div>    </div>      <div class="form-group">          <label class="control-label col-lg-3">&nbsp;</label>      <div class="col-lg-1">          <input type="hidden" value="false" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][_destroy]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0_header_tabs__destroy"><a class="btn btn-danger btn-xs rmhdrtab remove_nested_fields" data-association="header_tabs" href="javascript:void(0)"><i class="fa fa-close"></i></a>      </div>      <div class="col-lg-6 header_tabs">          <input placeholder="Write Tab Name" class="form-control form-ctr100 required" require="true" style="width:100%;" type="text" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][tab_name]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0_header_tabs_tab_name">          <div class="error"></div>      </div>      <div class="col-lg-2 header_tabs">          <input class="form-control form-ctr2 required" min="1" require="true" type="text" value="1" name="webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0][position]" id="webpage_section_headers_attributes_0_header_attributes_header_tabs_attributes_0_header_tabs_position">      </div>    </div>  </div>  

check - webpage[section_headers_attributes][0][header_attributes][header_tabs_attributes][0]

the index value [header_tabs_attributes][0] are same for tabs.

Can you please why is it same ? and what is the solutions ?

Update 2 - Code for the form.

          <%= nested_form_for webpage, html: {class: 'form-horizontal header-validation-webpage'}, remote: true do |form_webpage| %>                <%= hidden_field_tag :type, params[:type] %>                <%= form_webpage.fields_for :sections do |form_section| %>                                <div class="form-group">                                  <%= form_section.label :name, class: 'control-label col-lg-3' %>                                  <div class="col-lg-8">                                                    <%= form_section.text_field :name, placeholder: 'Write your section name!', class: 'form-control' %>                                  </div>                              </div>                                <div class="form-group">                                  <%= form_section.label :position, class: 'control-label col-lg-3' %>                                  <div class="col-lg-8">                                      <%= form_section.number_field :position, placeholder: 'Position', class: 'form-control', min: 1 %>                                  </div>                              </div>                    <%= form_section.fields_for :header do |form_header| %>                                  <legend><small>Tab Name & Position Detail</small></legend>                      <div class="header_tabs_forms">                      <%= form_header.fields_for :header_tabs, :wrapper => false do |form_htab| %>                                                  <%# index = Time.now().strftime("%d%m%Y%I%M%S%3N") %>                                      <div class="form-group">                                          <label class="control-label col-lg-3">&nbsp;</label>                                      <div class="col-lg-1">                                          <%= form_htab.link_to_remove "<i class='fa fa-close'></i>".html_safe, class: 'btn btn-danger btn-xs rmhdrtab' %>                                      </div>                                      <div class="col-lg-6 header_tabs">                                          <%= form_htab.text_field :tab_name, placeholder: 'Write Tab Name', class: 'form-control form-ctr100 required', require: true, style: 'width:100%;' %>                                          <div class='error'><%= display_error_messages webpage.errors, [:'header.header_tabs.tab_name'] %></div>                                      </div>                                      <div class="col-lg-2 header_tabs">                                          <%= form_htab.text_field :position, class: 'form-control form-ctr2 required', min: 1, require: true %>                                      </div>                                    </div>                      <% end %>                      </div>                      <p class="text-right">                          <%= form_header.link_to_add "<i class='fa fa-plus'></i> Add New Tab".html_safe, :header_tabs, data: {target: '.header_tabs_forms'} %>                      </p>                  <% end %>                <% end %>                        <hr>                        <div class="form-group">                           <div class="col-lg-offset-3 col-lg-9">                              <%= form_webpage.submit 'Save', class: 'btn btn-primary', data: {disable_with: 'Loading...'} %>                          </div>                        </div>              <% end %>  

ElasticSearch - Dealing with problems with de-normalized data

Posted: 19 Oct 2016 08:00 AM PDT

I built an auction system that uses ElasticSearch. It has 3 models, users, auctions and bids. A user can post an auction and can also bid on other auctions.

One of my first use cases for searching is for searching bids. Aside from searching by id, user_id, price, etc, I've encountered an interesting use case. I want to be able to search for a user's name and it should return all my bids from all the auctions posted by that user.

e.g. When I search for "John", it would get all the bids that I have sent for all the auctions posted by the user "John".

Here's what the index looks like:

Bids  - id (not analyzed)  - user_id (not analyzed)  - price (not analyzed)  - auction_user_name (uses ngrams)  

I have a couple of problems with this index:

  1. Bids has a lot of rows (10M+) and having n-grams on auction_user_name takes up a lot of space. I'm thinking if this data really should be de-normalized in a single index with a single type, or if there are any alternatives that is more appropriate (parent-child types)?

  2. Some users are very active and can have thousands of bids. If one of them changes their name, it will cause thousands of updates to the bids index. This is not ideal and due to the duplicates, it can result to a write-heavy index which can be vulnerable to denial of service.

Are there known solutions for these two problems? I'm sure there's some trade-off I can do to solve this.

I have seen some suggestions on: https://www.elastic.co/guide/en/elasticsearch/guide/current/relations.html

The methods are not as elegant as I imagined so I'm interested if there are more ways to tackle the problem.

guys can anyone help how to decode this in ruby on rails

Posted: 19 Oct 2016 07:34 AM PDT

guys can anyone help how to decode this in ruby on rails

MDExMDExMTEwMTExMDAwMDAxMTAwMTAxMDExMDExMTAwMDEwMDAwMDAxMTEwMDExMDExMDAxMDEwMTExMDAxMTAx MTAwMDAxMDExMDExMDEwMTEwMDEwMQ==

How do I check if a value is present within my array? - Rails 4

Posted: 19 Oct 2016 07:41 AM PDT

Can one kindly advise me how i do check if my array includes a value.

  • i have an array attendees = social.attendances
  • i am trying to check if the user = User.find(4) is present within the attendees array

Terminal

user = User.find(4)    User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]   => #<User id: 4, email: "emma@gmail.com">       social = Social.find(10)    Social Load (0.3ms)  SELECT  "socials".* FROM "socials" WHERE "socials"."id" = ? LIMIT 1  [["id", 10]]   => #<Social id: 10, title: "How to successfully fundraise">       attendees = social.attendances   => #<ActiveRecord::Associations::CollectionProxy [#<user_id: 10>, #<user_id: 4>, #<user_id: 14>, #<user_id: 9>, #<user_id: 6>]>   

i tried the below:

i tried the below in the terminal but no luck

 attendees.include?(user_id:4)   => false     attendees.include? "user_id:4"   => false  

Spree VAT included prices with promo

Posted: 19 Oct 2016 07:28 AM PDT

We have Spree application, version 3.0.0. Item prices are in GBP and EUR, and include 20% VAT. I have created promo, with 25% discount on specific taxon.

When code is applied on item, updated total calculated incorrectly:

Price with VAT - discount - total

We want:

Price before VAT - discount - VAT - total

I've checked the docs and github and found this issue and PR https://github.com/spree/spree/issues/6475

What I noticed, that everything works correctly once I add another item to cart.

Not sure what to do next.

Passing a parameter received in link_to to different actions in controller

Posted: 19 Oct 2016 07:38 AM PDT

I have an Item model as below.

class Item < ApplicationRecord    belongs_to :item_type, :class_name=>ItemType, :foreign_key=>"item_type_id"  end  

and a RecipeIngredient model as below

class RecipeIngredient < ApplicationRecord    belongs_to :item, :class_name=>Item, :foreign_key=>"item_id"    belongs_to :ingredient, :class_name=>Ingredient, :foreign_key=>"ingredient_id"    validates_numericality_of :quantity  end  

From the index view of items, I am passing the item_id to the index view of recipe_ingredients as below

<td><%= link_to 'Add Recipe', recipe_ingredients_path(:item_id =>item.id) %></td>  

and the index view of recipe_ingredients only displays those ingredients which belong to the item with item_id as received in URL. For that the controller for RecipeIngredient is like this.

 def index      @recipe_ingredients = RecipeIngredient.where(:item_id => params[:item_id])    end  

now I am trying to pass the same item_id to newrecipe ingredient form from the index page of recipe ingredient like this.

<%= link_to 'New Recipe Ingredient', new_recipe_ingredient_path(:item_id => @item_id) %>  

and the whole controller file for recipe ingredients, including new is given below.

class RecipeIngredientsController < ApplicationController    before_action :set_recipe_ingredient, only: [:show, :edit, :update, :destroy]      # GET /recipe_ingredients    # GET /recipe_ingredients.json    def index      @recipe_ingredients = RecipeIngredient.where(:item_id => params[:item_id])    end      # GET /recipe_ingredients/1    # GET /recipe_ingredients/1.json    def show    end      # GET /recipe_ingredients/new    def new      @recipe_ingredient = RecipeIngredient.new(:item_id => params[:item_id])    end      # GET /recipe_ingredients/1/edit    def edit    end      # POST /recipe_ingredients    # POST /recipe_ingredients.json    def create      @recipe_ingredient = RecipeIngredient.new(:item_id => params[:item_id])        respond_to do |format|        if @recipe_ingredient.save          format.html { redirect_to @recipe_ingredient, notice: 'Recipe ingredient was successfully created.' }          format.json { render :show, status: :created, location: @recipe_ingredient }        else          format.html { render :new }          format.json { render json: @recipe_ingredient.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /recipe_ingredients/1    # PATCH/PUT /recipe_ingredients/1.json    def update      respond_to do |format|        if @recipe_ingredient.update(recipe_ingredient_params)          format.html { redirect_to @recipe_ingredient, notice: 'Recipe ingredient was successfully updated.' }          format.json { render :show, status: :ok, location: @recipe_ingredient }        else          format.html { render :edit }          format.json { render json: @recipe_ingredient.errors, status: :unprocessable_entity }        end      end    end      # DELETE /recipe_ingredients/1    # DELETE /recipe_ingredients/1.json    def destroy      @recipe_ingredient.destroy      respond_to do |format|        format.html { redirect_to recipe_ingredients_url, notice: 'Recipe ingredient was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_recipe_ingredient        @recipe_ingredient = RecipeIngredient.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def recipe_ingredient_params        params.require(:recipe_ingredient).permit(:item_id, :ingredient_id, :quantity)      end  end  

but the URL to new recipe ingredient does not contain the parameter and hence the form as below which has a hidden field (mandatory) of item_id gives error of field being empty.

<%= form_for(recipe_ingredient) do |f| %>    <% if recipe_ingredient.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(recipe_ingredient.errors.count, "error") %> prohibited this recipe_ingredient from being saved:</h2>          <ul>        <% recipe_ingredient.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>      <div class="field">      <%= f.hidden_field :item_id %>    </div>     <div class="field">      <%= f.label :ingredient_id %>      <%= f.collection_select :ingredient_id, Ingredient.all, :id, :ingredient %>    </div>      <div class="field">      <%= f.label :quantity %>      <%= f.text_field :quantity %>    </div>      <div class="actions">      <%= f.submit %>    </div>  <% end %>  

Getting records where attributes have certain value

Posted: 19 Oct 2016 07:42 AM PDT

I have a project with a model Person, a person has many Pets, and a Pet and a Boolean attribute Mammal, Id like to be able to retrieve all people whose have at least one pet who is a mammal, but I'm not sure how to do this, I've tried:

Person.includes(:pets).where(pets: {mammal: true})  

but it doesn't seem to work. What is the best way for me to do this?

Rails: Load a div in bootstrap modal, after the modal has been displayed fully

Posted: 19 Oct 2016 07:21 AM PDT

I have a fairly simple question. I have a bootstrap modal with a div that I want to load only once the modal has fired. I am using..

 $('#ResultsModal').on('shown.bs.modal', function (event) {      $('#ResultsChart').show()    })  

The div is nothing particularly special:

<div id = "ResultsChart">      Some interesting results here  </div>  

The point is I don't want a "show", "hide" solution. I want the div to actually load after the modal. I had thought about using a partial and loading that in using a .js.erb file but I couldn't see how that could be done from the button the fires the modal. I suspect I am making this harder than it needs to be.

OR in where clause when working with nested includes or joins with association

Posted: 19 Oct 2016 07:16 AM PDT

I have to use OR in where clause when working with nested includes with association. i have ruby query some thing as :

Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers]).where(:categories => { category_tag: 'Dry'},:location_id =>12,:inventory_tiers => {:tier => 1}),modifiers:{category_tag:"Wet"},modifier_tiers:{tier:1})  

in which where clause uses AND for all condition. but i want to use OR for last two condition something as :

Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers]).where("categories.category_tag=? AND location_id=? AND inventory_tiers.tier = ? OR modifiers.category_tag=? OR modifier_tiers.tier=?", "Wet",12,1,"Wet",1).select("inventories.id,inventories.name,inventories.photo,inventory_tiers.sell_price, modifiers.id,modifiers.name,modifiers.price,modifier_measures.id as measure_id,modifier_measures.name as measure,modifier_measures.price as measure_price,modifier_measures.measure_value")  

but its not working. how i can write ?.

Rails -- Export CSV failing if there is a blank field

Posted: 19 Oct 2016 07:23 AM PDT

I have code in my Rails app that allows me to export a CSV file. It works fine unless there is a record that has a field with no value in it. In that case it fails. As an example, the specific failure I'm getting is saying something liek "No Method Error" and it specifically references "address_line_1" because there are some users with no address_line_1. That is just one example though. Really all fields should be protected against potential blanks. Here is the code:

def download_kids_csv        @csv_headers = ['First',                      'Last',                      'Child First',                      'Child Last',                      'Parent Email',                      'School',                      'Class',                      'Address',                      'City',                      'State',                      'Zip',                      'Parent Phone']        @kid_data = []        @school = School.find(params[:school_id])        @school.classrooms.each do |classroom|          classroom.kids.includes(:users).each do |kid|              kid.users.each do |parent|                  @kid_data << {                      first: parent.first_name,                      last: parent.last_name,                      child_first: kid.first_name,                      child_last: kid.last_name,                      parent_email: parent.email,                      school: @school.name,                      class: classroom.classroom_name,                      address: parent.addresses.first.address_line_1,                      city: parent.addresses.first.city,                      state: parent.addresses.first.state,                      zip: parent.addresses.first.zip_code,                      parent_phone: parent.phones.first.phone_number                  }              end          end      end        respond_to do |format|          format.csv do            headers['Content-Disposition'] = "attachment; filename=\"#{@school.name.downcase.gsub(' ', '-')}-data.csv\""            headers['Content-Type'] ||= 'text/csv'          end      end  end  

(Rails) Remote form responds with .js on update but not on create

Posted: 19 Oct 2016 07:06 AM PDT

I have a simple remote form logic in my Rails app to respond to new, create, edit and update actions of my controller with AJAX. My form_for...remote => true responds with format.js, but not to my successful create-actions. I use the same form-partial for all, my update-action responds with .js and my create-action responds with .js only if the saving was not successful. If I submit a valid form for a new item, teh app throws an ActionController::UnknownFormat error. How can this only concern the successful create-action?

I have the <%= javascript_include_tag 'application' %> and <%= csrf_meta_tags %> included and below is my code:

form-partial:

# variable remote_form is true  <%= form_for(shop_item, :remote => remote_form, :authenticity_token => true) do |f| %>  ...  <% end %>  

controller:

def create    @shop_item = ShopItem.new(shop_item_params)    if @shop_item.save      respond_to do |format|        format.js do          flash.now[:success] = "New Item #{@shop_item.title} created"        end      end    else      respond_to do |format|        format.js { render 'new' }      end    end  end    def edit    @shop_item = ShopItem.find(params[:id])    respond_to do |format|      format.js    end  end    def update    @shop_item = ShopItem.find(params[:id])    if @shop_item.update_attributes(shop_item_params)      @shop_item.reload      respond_to do |format|        format.js do          flash.now[:success] = "Updated #{@shop_item.title}"        end      end    else      respond_to do |format|        format.js { render 'edit' }      end    end  end  

create.js.erb:

if ($('#flashes').length > 0) {    $('#flashes').replaceWith('<%= j(render :partial => "shared/flashes") %>');  } else {    $('#session').append('<%= j(render :partial => "shared/flashes") %>');  }    $('#shop-items').prepend('<%= j(render @shop_item) %>');  

server:

ActionController::UnknownFormat (ActionController::UnknownFormat):      app/controllers/shop_items_controller.rb:20:in `create'  ...  

Thanks!

Rails 4 hash accessing values returns nil

Posted: 19 Oct 2016 07:14 AM PDT

I seem to be stuck trying to access hash values coming from a csv file and could use a different pair of eyes to point out the obvious mistake I'm making. Here is the relevant code:

  CSV.foreach(filename, headers: true, header_converters: :symbol, converters: :all) do |row|    data = row.to_hash    id = data['studentid'] # (have also tried id = data[':studentid'] but there are no :'s in the csv file headers, and double quotes instead of single)    title = data['title'] # also (title = data[:title'])       logger.debug "data param: #{data.inspect}"       logger.debug "data title param: #{title.inspect}"       logger.debug "data studentid param: #{id.inspect}"  

From the log file: (valid data x'ed out or fake - note studentid comes in as a fixnum)

data param: {:lastname=>"XXXX", :firstname=>"XXXXX", :title=>"XXXXXXX", :studentid=>123456, :date=>"XXXXXXXXXX"}  data title param: nil  data studentid param: nil  

Rails 4.x Ruby 2.x OS Ubuntu Ideas?

Search capability combined with xls formatting

Posted: 19 Oct 2016 06:57 AM PDT

I have a download icon beside a table of results. When clicked this will generate an excel file containing the table results. The table also has search capabilities so when you search the table is updated and if you then click download this will download only those records conforming to the search. Currently the download works when no search is performed. When a search is performed and I attempt to download it still downloads the full list of records.

Here is the link, not that it is needed but to clarify:

= link_to '<i class="glyphicon glyphicon-cloud-download"></i>'.html_safe, admin_campaigns_path( format: :xlsx), title: "Download Campaign XLS", rel: 'tooltip'  

Here is my controller:

def index    @search      = Campaign.search(params[:q])    @campaigns = @search.result    respond_to do |format|      format.html{@campaigns = @search.result.page(params[:page]||1)}      format.xlsx{render xlsx: 'Campaigns'}    end  end  

Finally here is the campaign.xlsx.axlsx

require 'axlsx'  xlsx_package = Axlsx::Package.new  wb = xlsx_package.workbook  wb.add_worksheet(name: "Campaigns") do |sheet|    style1 = sheet.styles.add_style(:bg_color => "00619B", :fg_color => "FFFFFF", :b => "true")    sheet.add_row ["Name", "Operator", "Partner", "Status","Revenue Share","Service Type","Free Trial","Partial Charging","Service Code","Description","Created","Last Updated"], :style => style1    @campaigns.each do |campaign|      sheet.add_row [campaign.name, campaign.operator.try(:code).try(:upcase),campaign.try(:partner).try(:company_name),campaign.status,campaign.merchant_revenue,campaign.service_type,campaign.trial,campaign.partial,campaign.service_code,campaign.description.split[0...6].join(' '),campaign.created_at.try(:strftime, " %d %b %Y -  %H:%M "),campaign.updated_at.try(:strftime, " %d %b %Y -  %H:%M ")]    end  end  

I was trying to play around with the structure of my respond_to block but am having no luck. Any help is appreciated.

Create website and child page simultaneously in Rails 5

Posted: 19 Oct 2016 07:26 AM PDT

On my homepage, I'm trying to set it up so when you click the "Get started" button, a website record is created, but also a page belonging to that website is created, and you're redirected to the page.

This is what I have so far. The website record is being created but the page is not being created.

Models

class Page < ApplicationRecord      belongs_to :website  end    class Website < ApplicationRecord      has_many :pages, :dependent => :destroy        accepts_nested_attributes_for :pages  end  

Homepage controller

class MarketingPagesController < ApplicationController      def home          @website = Website.new          @website.pages.build      end  end  

Website controller

class WebsitesController < ApplicationController      def create          @website = Website.new(creation_params)            if @website.save              redirect_to @website.Page.first          else              render :new          end      end    private        def shared_params          [:name]      end        def creation_params          params.require(:website).permit(*shared_params)      end        def update_params          params.require(:website).permit(*shared_params)      end  end  

Page Controller

class PagesController < ApplicationController        def create          @page = Page.new(creation_params)            if @page.save              redirect_to @page          else              render :new          end      end        def show          @page = Page.find(params[:id])          @templates = Template.all      end    private        def shared_params          [:name, :website_id]      end        def creation_params          params.require(:page).permit(*shared_params)      end        def update_params          params.require(:page).permit(*shared_params)      end  end  

Website form on homepage

<%= form_for @website do |f| %>      <%= f.hidden_field :name, value: "Untitled site" %>      <%= f.fields_for :pages do |builder| %>          <%= builder.hidden_field :name, value: "Untitled page" %>      <% end %>      <%= f.submit "Create Website" %>  <% end %>  

devise_token_auth method to create user instead of API

Posted: 19 Oct 2016 06:42 AM PDT

i am using devise_token on ruby on rails web app. I have the requirement to create/register user in the app from other than api. Actually i want to sign-up users through other pipe coming through MQTT bus.

I am not able to find a module method that can create can create/register.

From the official documentation i can see that maybe devise don't offer method for registering users. I have worked with other platforms/libraries like Microsoft owin that also expose User.Identity.create method within the app.

The answer for this question on stack do talk a bit about this, and points to modifying the controller method of the devise for registration.

Can anyone help me with this as it looks a lot of effort for me to do this workaround as mentioned in the answer.

Rails Client-Side Validations with Chosen-Select

Posted: 19 Oct 2016 06:39 AM PDT

I'm using client-side-validations gem for rails 5. It works fine, except to chosen-select. If I remove the "chosen-select" class, it works properly. Doing some research, found that the problem is the select for chosen is hidden, so they suggest to set the default on validator:

$.validator.setDefaults({ ignore: ":hidden:not(select)" }) //for all select  

That wouldn't work 'cause $.validator is not defined. Also saw something suggesting to change the validation to the attribute_name_id instead of association_name. Didn't work either. I have the validate true on form builder, and the problem is really about chosen, 'cause as I said, removing the class, it works fine. Any ideas? thanks!

Getting record where the first set of characters in attribute matches

Posted: 19 Oct 2016 06:42 AM PDT

I have a model with a string attribute, the attribute can have values 'abc', 'def', 'ghi' or 'jkl' + count I need to get all records with the value 'jkl' + count. I was hoping something like:

Model.where(status[0..2]: 'jkl')  

Would work, but it seems like it doesn't, is there a good way for me to do this?

send_file/send_data not sending file for downloading

Posted: 19 Oct 2016 06:31 AM PDT

i'm using rails 3.2.22.4 and ruby 2.2.4. i'm testing send_file feature. I get "file sent" in server logs but i cant see it is getting downloaded in browser. Save button click will call this action.

def save_trunk_logs    data = "Hello World!"    file = "my_file.txt"    File.open(file, "w"){ |f| f << data }    send_file( file )  end   

server logs says below message.

Sent file my_file.txt (1.0ms)  Completed 200 OK in 6.0ms (ActiveRecord: 0.0ms)  

I also tried with adding extra options like below

:type => 'text/plain; charset=UTF-8', :disposition => 'attachment'  

every time i get same server message that file is sent. Any help will be appreciated. Thanks in advance.

geocode 2 addresses with geocoder gem

Posted: 19 Oct 2016 07:15 AM PDT

I'm trying to geocode 2 addresses which are asked in 1 form.

  <%= f.input :kotadres %>    <%= f.input :location %>  

Both of them work with Google Autocomplete like this:

<script>    var input = document.getElementById('student_location');    var autocomplete = new google.maps.places.Autocomplete(input,{componentRestrictions: {country:'be'}});    google.maps.event.addListener(autocomplete, 'place_changed', function(){    var place = autocomplete.getPlace();    })  </script>    <script>    var input = document.getElementById('student_kotadres');    var autocomplete = new google.maps.places.Autocomplete(input,{componentRestrictions: {country:'be'}});    google.maps.event.addListener(autocomplete, 'place_changed', function(){    var place = autocomplete.getPlace();    })  </script>  

This works perfectly fine, because both addresses are stored in the database.

Now I want to geocode these 2 addresses in my database. It already works for 50%, because for some reason it always geocodes :kotadres into a :latitude and :longitude column but I have no idea why it geocodes only this attribute and not the :location attribute.

This is my Students table:

  create_table "students", force: :cascade do |t|      t.string   "location"      t.float    "latitude"      t.float    "longitude"      t.string   "kotadres"    end  

I know I have to create 2 new columns to store 2 new latitude and longitude values for :location but I was wondering how to do this.

Basically I want to understand why it only geocodes the :kotadres attribute and not the :location attribute. I tried the following things:

  • swith both input fields in the form (result: only :kotadres gets geocoded)
  • delete the :kotadres input field (result: :location doesn't get geocoded)

My Student model looks like this:

geocoded_by :location  after_validation :geocode, if: :location_changed?    geocoded_by :kotadres  after_validation :geocode, if: :kotadres_changed?  

So if someone knows how to geocode these 2 addresses or if someone knows why it always geocodes the :kotadres attribute, I'm more than happy to know the answers.

Rails inline pdf attachment in email can not display on Iphone

Posted: 19 Oct 2016 06:36 AM PDT

I have successfully added pdf file as inline attachment to email. My problem is, When I add png file I can show that file inline as;

<%= image_tag attachments['logo.png'].url, :style => "display: block; width: 80px;"  %>  

and in my mailer;

attachments.inline['logo.png'] = File.read(Rails.root.join('app/assets/images/logo.png'))  

When I add as pdf;

attachments.inline['Delivery_Document.pdf'] = File.read(Rails.root.join('app/assets/folder/Delivery_Document.pdf'))  

in my mailer it works on the desktop, I can see the attachment.

But when I look at the same email from iphone, I can not see the attachment. I think it is because I do not add inline as

<%= image_tag attachments['logo.png'].url, :style => "display: block; width: 80px;"  %>  

But how can I add pdf file like that?

How to restart Rails and Apache

Posted: 19 Oct 2016 07:37 AM PDT

How do I go across restarting Rails and Apache on a server from the Terminal app on a Mac?

I've looked at tutorials, but they haven't seemed to help.

I was told to enter reboot into Terminal, but that just said Operation not permitted.

activeadmin resource(employee) creates multiple profiles(another resource)instead of having has_one relationship

Posted: 19 Oct 2016 06:42 AM PDT

Employee.rb (active admin resource,has_one :profile)

    ActiveAdmin.register Employee do          # See permitted parameters documentation:        # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters        #       permit_params  :email,:password,:password_confirmation,profile_attributes:[:name,:date_of_birth,:contact,:current_address,:permanent_address]        # or        #        # permit_params do        #   permitted = [:permitted, :attributes]        #   permitted << :other if params[:action] == 'create' && current_user.admin?        #   permitted        # end        index do                  column :email          column 'Name' do |f|            f.profile.name     if !f.profile.nil?          end            column 'Birthday' do |f|            f.profile.date_of_birth     if !f.profile.nil?          end            column 'Contact' do |f|            f.profile.contact    if !f.profile.nil?          end            column 'Current address' do |f|            f.profile.current_address    if !f.profile.nil?          end            column 'Permanent Address' do |f|            f.profile.permanent_address     if !f.profile.nil?          end          actions        end          form do |f|          f.semantic_errors *f.object.errors.keys          f.inputs "Login Credentials" do            f.input :email            f.input :password            f.input :password_confirmation          end          f.actions        end          show do          attributes_table do            row :email          end          attributes_table_for employee.profile do             row :name            row :date_of_birth            row :contact            row :current_address            row :permanent_address          end          end        end  

profile.rb (Activeadmin resource,belongs_to:employee)

This is getting created multiple times

  ActiveAdmin.register Profile do            permit_params :name, :date_of_birth, :contact, :employee_id, :current_address, :permanent_address        form do |f|          f.semantic_errors *f.object.errors.keys          f.inputs "Employee Profile" do            f.input :employee             f.input :name            f.input :date_of_birth, as: :datepicker            f.input :contact            f.input :current_address            f.input :permanent_address          end           f.actions         end          show do          attributes_table do            row :name            row :date_of_birth            row :contact            row :current_address            row :permanent_address          end           end      end  

They both are activeadmin resource.How can i restrict it to one profile per employee.

Rspec testing 'create' conversation post route with Mailboxer error: ' param is missing or the value is empty: conversation'

Posted: 19 Oct 2016 05:25 AM PDT

I've set up and install Mailboxer with a conversations controller and am trying to use Mailboxer and Rails simply as an API. I am trying to test my CREATE conversations method however am continually returned an error:

'param is missing or the value is empty: conversation'  

Here is my conversations controller:

class ConversationsController < ApplicationController      before_action :authenticate_user!      def create      @recipient = User.where(id: conversation_params[:recipient])      respond_with current_user.send_message(@recipient, conversation_params[:body], conversation_params[:subject]).conversation    end      def show      render json: conversation.receipts_for(current_user)      conversation.mark_as_read(current_user)    end      def reply      respond_with current_user.reply_to_conversation(conversation, message_params[:body])    end      def trash      respond_with conversation.move_to_trash(current_user)    end      def untrash      respond_with conversation.untrash(current_user)    end      private      def conversation_params      params.require(:conversation).permit(:recipient, :subject, :body)    end      def message_params      params.require(:message).permit(:body, :subject)    end    end  

and here is my routes file:

Rails.application.routes.draw do    mount_devise_token_auth_for 'User', at: 'auth', defaults: { format: :json }    resources :users, only: [:show]    resources :posts    root 'posts#index'      get "mailbox/inbox" => "mailbox#inbox", as: :mailbox_inbox    get "mailbox/sent" => "mailbox#sent", as: :mailbox_sent    get "mailbox/trash" => "mailbox#trash", as: :mailbox_trash      resources :conversations do      member do        post :reply        post :trash        post :untrash      end    end  end  

and finally here are my tests:

require 'rails_helper' require 'pry'

describe ConversationsController, 'testing conversations' do    let(:json) { JSON.parse(response.body) }    let(:auth_error) {{"errors"=>["Authorized users only."]}}    let(:new_message_params) { {recipient: @tom, body:"Goodbye", subject:"Goodbye"} }    let(:description_edited) { {description: 'Edited'} }      before(:each) do      @bob = create :user      @tom = User.create(name: "tom", email:"tom@tom.com", password: "1234567890", password_confirmation: "1234567890")      @auth_headers_tom = @tom.create_new_auth_token      @auth_headers_bob = @bob.create_new_auth_token      @message = @bob.send_message(@tom,"Hello","Hello")    end      it 'displays existing messages', type: :request do      get '/mailbox/inbox', {}, @auth_headers_tom      expect(json[0]['subject']).to eq("Hello")    end      it 'allows user to create a conversation', type: :request do      post '/conversations.json', new_message_params, @auth_headers_bob      get '/mailbox/inbox', {}, @auth_headers_tom      expect(json[1]['subject']).to eq("Goodbye")    end      it 'displays existing messages requests', type: :request do      get '/mailbox/inbox', {}, {}      expect(json).to eq(auth_error)    end  end  

The first test 'displays existing messages' passes however the second test is failing with the error param is missing etc.

I have managed to successfully create a conversation using the seeds file and in the test 'before' using 'send_message' however sending a POST JSON to the route is bringing back the error.

Any help appreciated!

spree install error: "rails g spree:install --user_class=Spree::User" not doing anything

Posted: 19 Oct 2016 05:24 AM PDT

I have create a new rails app using this command:

rails new store

rails version is: 4.2.

Ruby Version: `rvm rubies

ruby-2.1.2 [ x86_64 ] ruby-2.2.0 [ x86_64 ] =* ruby-2.2.2 [ x86_64 ]`

Following is the Gemfile:

 source 'https://rubygems.org'   # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'   gem 'rails', '~> 4.2.6'   # Use sqlite3 as the database for Active Record   gem 'sqlite3'   # Use Puma as the app server   gem 'puma', '~> 3.0'   # Use SCSS for stylesheets   gem 'sass-rails', '~> 5.0'   # Use Uglifier as compressor for JavaScript assets   gem 'uglifier', '>= 1.3.0'   # Use CoffeeScript for .coffee assets and views   gem 'coffee-rails', '~> 4.2'   # See https://github.com/rails/execjs#readme for more supported runtimes   # gem 'therubyracer', platforms: :ruby     # Use jquery as the JavaScript library   gem 'jquery-rails'   # Turbolinks makes navigating your web application faster. Read more:                     https://github.com/turbolinks/turbolinks   gem 'turbolinks', '~> 5'   # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder   gem 'jbuilder', '~> 2.5'   # Use Redis adapter to run Action Cable in production   # gem 'redis', '~> 3.0'   # Use ActiveModel has_secure_password   # gem 'bcrypt', '~> 3.1.7'     # Use Capistrano for deployment   # gem 'capistrano-rails', group: :development     group :development, :test do     # Call 'byebug' anywhere in the code to stop execution and get a debugger console     gem 'byebug', platform: :mri   end     group :development do     # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.     gem 'web-console'     gem 'listen', '~> 3.0.5'     # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring     gem 'spring'     gem 'spring-watcher-listen', '~> 2.0.0'   end     gem 'spree', '~> 3.1.0'   gem 'spree_auth_devise', '~> 3.1.0'   gem 'spree_gateway', '~> 3.1.0'     # Windows does not include zoneinfo files, so bundle the tzinfo-data gem   gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

Bundle install works fine, But when I try to follow getting started and run this command

rails g spree:install --user_class=Spree::User

Nothing happens at all.

Please let me know what can be wrong?

1 comment:

  1. very informative blog and useful article thank you for sharing with us , keep posting Ruby on Rails Online Course

    ReplyDelete