Wednesday, June 1, 2016

Enable Heroku labs feature in Heroku review apps | Fixed issues

Enable Heroku labs feature in Heroku review apps | Fixed issues


Enable Heroku labs feature in Heroku review apps

Posted: 01 Jun 2016 06:50 AM PDT

I have a Heroku app that has review apps enabled. The review apps are configured based on the app.json file in the root directory of my application. I'm able to add addons but I don't seem to be able to enable the runtime-dyno-metadata labs feature. Below is just one of the many ways I've tried to get this working...

{    "name": "Foo",    "scripts": {      "postdeploy": "bundle exec rake db:migrate db:seed"    },    "formation": {      "worker": {        "quantity": 1      },      "web": {        "quantity": 1      }    },    "addons": [      "heroku-postgresql",      "heroku-redis",    ],    "labs": [      "runtime-dyno-metadata"    ],    "buildpacks": [      {        "url": "https://github.com/heroku/heroku-buildpack-nodejs.git"      },      {        "url": "https://github.com/heroku/heroku-buildpack-ruby.git"      }    ]  }  

ArgumentError: parent directory is world writable but not sticky (bundle install)

Posted: 01 Jun 2016 06:41 AM PDT

Link to github for error printout

When i try to bundle install I receive the above error. I have tried what other posts suggest and the github community doesn't know the answer.

I am running Arch and am using zsh for my shell.

Updated Environment:

Bundler 1.12.5

Rubygems 2.5.1

Ruby 2.3.1p112 (2016-04-26 revision 54768)[x86_64-linux]

GEM_HOME /usr/lib/ruby/gems/2.3.0

GEM_PATH /usr/lib/ruby/gems/2.3.0:/home/.gem/ruby/2.3.0

Git 2.8.3

open_gem (1.5.0)

Thanks in advance!

Where do I set template for rails error messages?

Posted: 01 Jun 2016 07:01 AM PDT

I want rails to show error message

Field <field name> can't be blank  

but using standard means I get

<field name> Field <field name> can't be blank  

Here's a minimal example reproducing the problem:

rails new test  cd test  rails g scaffold user name  rake db:migrate  

Add validation to app/models/user.rb:

class User < ActiveRecord::Base    validates :name, presence: true  end  

Edit config/locale/en.yml to be:

en:    activerecord:      attributes:        user:          name: "Name"      errors:        models:          user:            attributes:              name:                blank: "Field %{attribute} can't be blank"  

After this start the server

rails s  

point browser to http://localhost:3000/users/new and press "Create User" button. You'll get:

enter image description here

Apparently, there's another template somewhere, which says something like

%{attribute} %{message}  

but I can't find it in rails code.

Rails no route match

Posted: 01 Jun 2016 06:47 AM PDT

I am following this restful authentication tutorial


It is saying ActionController::RoutingError (No route matches [GET] "/events"):

Rails.application.routes.draw do    api_constraints = if Rails.env.production?                         {subdomain: 'api'}                      else                        {}                      end    #api_constraints = {subdomain: 'api'}    #namespace :api, path: '', constraints: {subdomain: 'api'} do      namespace :api, constraints: api_constraints, defaults: {format: :json} do      namespace :v1 do        resources :events      end    end  

Create constraints in rails migrations

Posted: 01 Jun 2016 06:29 AM PDT

I have a migration that create a named constraint

execute(%Q{    ALTER TABLE dreamflore_clients      ADD CONSTRAINT unique_clients UNIQUE( client, no_adresse );  })  

But in schema.rb, rails turn this part into an index

add_index "dreamflore_clients", ["client", "no_adresse"], name: "unique_clients", unique: true, using: :btree  

The problem is we are using Apartment and newly created tenants have an index instead of the constraint and we are using the postgreSQL feature ON CONFLICT ON CONSTRAINT

For now the solution is to rollback some migrations and migrate again, but this is a really dirty hack

How to stop rails creating this index?

Nested attributes won't bind to model

Posted: 01 Jun 2016 06:48 AM PDT

I'm trying to allow nested attributes to be submitted with my model during a post. I'm using RubyMine as my IDE, and when debugging, I'm able to see the correct values that are being posted, but I can't figure out what they aren't then being set in the @model.

Models

class Product < ActiveRecord::Base    has_many :product_prices    accepts_nested_attributes_for :product_prices, allow_destroy: true  end  class ProductPrice < ActiveRecord::Base    belongs_to :product  end  

View Code

<%= form_for :model, url: products_path do |f| %>      <p>          <%= f.label :name %><br/>          <%= f.text_field :name %>      </p>        <table>          <%= f.fields_for :product_prices do |ff| %>              <tr>                  <td><%= ff.text_field :start_date %></td>                  <td><%= ff.text_field :end_date %></td>                  <td><%= ff.text_field :price %></td>                  <td><%= ff.check_box :_destroy %></td>              </tr>          <% end %>      </table>        <%= link_to 'Go Back', products_url %>      <%= f.submit 'Create' %>  <% end %>  

Controller

def update      @model = Product.includes(:product_prices).find(params[:id])        if @model.update(product_params)        redirect_to @model      else        render 'edit'      end    end  def product_params      params.require(:model).permit(:id, :name, :description, :is_active, product_prices_attributes: [:id, :product_id, :start_date, :end_date, :price, :_destroy])  end  

** Edit ** Below is my params structure:

'model': [    'name',     'description',     'is_active',    'product_prices': [          'start_date',           'end_date',           'price',           '_destroy']  ]  

model association with a scope for trashable module

Posted: 01 Jun 2016 06:48 AM PDT

I have a trashable concern that allows a user to trash ("delete") certain things.

The issue is that even though that item can be trashed, it still has to be referenced if you view something older. If you do that now it won't find that object as I've changed the default_scope to only show where trashed is false.

Here's my trashable module:

module Trashable    extend ActiveSupport::Concern      included do      default_scope   { where(trashed: false) }      scope :trashed, -> { unscoped.where(trashed: true) }      validates :trashed, inclusion: { in: [true, false] }    end      def trash      update_attribute :trashed, true    end  end  

now I have an Order model, where you can view an order. If we for example trash a product, I still want the user to be able to look at their order and see the product.

Now I'm not able to access that with a model association such as:

has_many :products and make it so that it includes both where trashed is false and true.

Does anybody know how to achieve this?

How to add progress bar in active admin gem

Posted: 01 Jun 2016 06:21 AM PDT

I am sending push notification to some user set on creation of question. I want to add progress bar so that user can see loading , when questions sent it should stop progress bar. I am not finding any way to do this in active admin. Following is my code :

    def create          question=PsychographicsQuestion.create(permitted_params["psychographics_question"])            for u in @@users              send_msg_through_gcm(u.to_i,"New PsychoGraphics question has been added.")          end            redirect_to admin_psychographics_question_path(:id=>question.id)      end  

Automatically convert hash keys to camelCase in JBuilder

Posted: 01 Jun 2016 06:11 AM PDT

I am using JBuilder version 2.4.1 and Rails 4.2.6. I am trying to serialize a complex object to JSON. The code looks as follows:

json.key_format! camelize: :lower    json.data_object @foo  

@foo looks like this:

{    key: 'value',    long_key: 'value'  }  

I expect it to be rendered as

{    "dataObject": {      "key": "value",      "longKey": "value"    }  }  

But instead it keeps the original hash keys, only converting data_object into camelCase

{    "dataObject": {      "key": "value",      "long_key": "value"    }  }  

So the question is: what is the proper way to camelize hash keys using JBuilder?

Rails save into 2 models

Posted: 01 Jun 2016 06:28 AM PDT

I have array of hashes and want to iterate through it and save into db

products = [      {          "currencyId"=>"UAH",          "categoryId"=>"9395236",          "picture"=> [              "http://images.ua.prom.st/427654530_w640_h640_cid2043281_pid296482296-1fdb5252.jpg",              "http://images.ua.prom.st/427654531_w640_h640_cid2043281_pid296482296-d1bd8ab8.jpg"          ],          "pickup"=>"true",          "delivery"=>"true",          "name"=>"VOX - Vox Ac15Vr ",          "vendor"=>"VOX",          "vendorCode"=>"D000951"},      {          other similar hash      },      {          other similar hash      }     ]  

so i want to do something like:

products.each do |product|      Product.create(name:product['name']...)        # and than save images to AWS , but i even don't imagine how to do it. Because i don't have saved product.  end      

I have the class Product with has_many :photos and class Photo with belongs_to :product

Is it possible?

How to make faye client on server side in rails app?

Posted: 01 Jun 2016 06:07 AM PDT

I have been working on Faye gem for couple of days. I have created Faye client at client-side using below code:

 var client = new Faye.Client('http://localhost:9292/faye');     $.get("/chatroom", function (data)      {       var UserId = data.user       client.subscribe("/message/"+UserId+"", function(data)        {          //rest of the code        });      })  

but I want this activity to be done on server side how to achieve this? Whenever a user gets login he should be subscribed to push server.

Rails - Flash message not displaying as intended using ruby case statement

Posted: 01 Jun 2016 06:26 AM PDT

In my rails app I am using various keys for flash. Some to display a message but also some to temporarily store data. I only want :notice, and :alert to display when present. Here is my code.

  <% flash.each do |type, message| %>      <% case type %>      <% when :notice, :alert %>        <% if message.is_a? Array %>          <% message.each do |msg| %>            <div class="alert alert-info">              <a class="close" data-dismiss="alert">&#215;</a>              <%= msg.html_safe %>            </div>          <% end%>        <% else %>          <div class="alert <%= flash_class type %>">            <a class="close" data-dismiss="alert">&#215;</a>            <%= message %>          </div>        <% end %>      <% end %>    <% end %>  

I can't figure out why nothing is displaying. It works fine when I remove the case statement but then every flash gets displayed which I don't want.

rails show page does not exist on staging but it does locally

Posted: 01 Jun 2016 05:48 AM PDT

Anyone know why could a show page on rails works locally but on staging I get the This page does not exist message? This is currently happening on my project and I have no ides what's going on.

Rails params from URL

Posted: 01 Jun 2016 06:01 AM PDT

i'm trying to parse an url. For example i have this link:

localhost:3000/keys?size=3&color=blue

I know there is so Utils.parse_nested_query but I don't find this .

Rails 4 - Yandex is not sending any mails

Posted: 01 Jun 2016 05:44 AM PDT

Rails 4.2.4 - I am using yandex for an email features. Right now mails are not sending, it will shows an error like

Net::SMTPFatalError: 554 5.7.1 Message rejected under suspicion of SPAM; https://yandex.ru/support/mail/spam/honest-mailers.xml 1464784342-4RQ5Kojp9R-WHMiWDV5  

In setup_mail.rb:

ActionMailer::Base.smtp_settings = {   :address => "smtp.yandex.ru",   :port => 465,   :domain => "yandex.ru",   :authentication => :login,   :user_name => "yandexemail@yandex.com",   :password => "password",   :ssl=> true,   :enable_starttls_auto=> true,   :tls=> true  }  

Sometimes mail will send properly with this configuration, sometimes above error will occurs. How can I fix this issue?

Also I have tried to fix it with the reference of Rails SMTP error, error will not be there but mail will not send.

Rails, after remote delete of item I get: First argument in form cannot contain nil or be empty

Posted: 01 Jun 2016 06:21 AM PDT

I want to delete an image on click. This is in my view

<%=form_for @area, url: areas_update_path, remote: true, html: {class: "form-horizontal",:multipart => true} do |f|%>  ....  <% @area.area_attachments.each do |a| %>    <%unless a.image.blank?%>      <%= link_to delete_area_attachment_path(a), :remote => true, :method => :delete do%>         <%= image_tag a.image_url(:thumb), class:"delete-image" %>                       <% end %>     <% end %>  <% end %>  ....  <% end %>  

After I click on an image, the image gets deleted, but I get

First argument in form cannot contain nil or be empty

In the first line of the code that I posted (@area I guess)

My delete_area_attachment method in my area_attachments_controller

def delete_area_attachment     @areaAttachment = AreaAttachment.find(params[:id])     @areaAttachment.destroy       respond_to do |format|       format.js     end  end  

I guess the @area variable has to be initialized, but why? What I am trying to delete is an area_attachment not an area, and I already initialized it, so what does the @area variable has to do with that?

How do I go about it here?

EDIT: my relative routes:

#Area Paths    get '/areas/new', to: 'areas#new', :as => 'areas_new'    post '/areas/create', to: 'areas#create', :as => 'areas_create'    get '/areas/:id/destroy', to: 'areas#destroy', :as => 'areas_destroy'    delete 'delete_area/:id', controller: 'areas', action: 'delete_area'    get '/areas/:id/edit', to: 'areas#edit', :as => 'areas_edit'    patch '/areas/:id/update', to: 'areas#update', :as => 'areas_update'      #Area Attachment Paths      delete 'delete_area_attachment/:id', controller: 'area_attachments', action: 'delete_area_attachment', :as => 'delete_area_attachment'  

My areas_controller

class AreasController < ApplicationController        before_action :set_areas      before_action :set_area, only: [:edit, :delete, :update, :destroy]          def new          @area = Area.new          @languages = Language.all          @area_attachment = @area.area_attachments.build      end        def create          @area = Area.new(area_params)            if @area.save && manage_strings              params[:area_attachments]['image'].each do |a|                  @area_attachment = @area.area_attachments.create!(:image => a, :area_id => @area.id)              end              @status = 'success'          else              @status = 'error'              @errormessages = @area.errors.full_messages          end          respond_to do |format|              format.js          end      end        def edit                end        def update          if @area.update(area_params) && manage_strings              params[:area_attachments]['image'].each do |a|                  @area_attachment = @area.area_attachments.create!(:image => a, :area_id => @area.id)              end              @status = 'success'          else              @status = 'error'              @errormessages = @area.errors.full_messages          end          respond_to do |format|              format.js          end      end        def delete_area          @area = Area.find(params[:id])          @area.destroy            respond_to do |format|              format.js          end      end        def find_area_by_id          area = Area.find(params[:id])          render json: area      end        protected        def news_list          respond_to do |format|              format.js          end      end            private        def area_params        params.require(:area).permit(:id, area_attachments_attributes: [:id, :area_id, :image])     end        def set_area          @area = Area.find_by_id(params[:id])          @languages = Language.all          @area_attachments = @area.area_attachments.all      end        def set_areas          @areas = Area.all      end        def manage_strings          if params[:area][:strings].any?              params[:area][:strings].each do |key,value|                  string = @area.article_localizations.find_or_initialize_by(:language_id => key.to_i)                  string.title = params[:area][:strings][key][:title]                  string.text = params[:area][:strings][key][:text]                  string.save              end          end       end    end  

How much ram memory I need for linux on virtual machine for rails

Posted: 01 Jun 2016 05:27 AM PDT

I am planing to install Ubuntu on virtual machine because it's better for rails developing than windows. But i only got 4 gb of ram memory. How much i should give to virtual machine, and which one is best?

What is the role of pipes inside Ruby? [duplicate]

Posted: 01 Jun 2016 05:34 AM PDT

This question already has an answer here:

I have a question as beginner. What is the role of a pipe? I mean this letter |

For example:

def change  create_table :articles do |t|    t.string :title  end  

What I'm looking to understand, how Ruby understand and communicate with the pipes ?

Ransack sorting deep associations is not working

Posted: 01 Jun 2016 05:15 AM PDT

I have many to many relations between models:

model1 has many model2  model2 has many model3  model3 has one model4  

sorting on attributes that come from model1 is working, but it didn't work neither for :

 `model2_attr` or `model2_first_model3_first_attr` or `model2_first_model3_first_model4_attr`  

Update: I have a grid and I want the sort to be based on string field inside the model3, and it comes from the decorator not from the model.

Performance issues when upgrading from ruby 1.9.3 to 2.2.2

Posted: 01 Jun 2016 04:56 AM PDT

When upgraded from ruby-1.9.3-p545 to ruby-2.2.2 we experienced a 50% drop in performance on our application. I have done a fair amount of reading around this and I suspect that this may be a result of the change in the way that ruby does garbage collection.

The confusing thing is that there have been no noticeable changes on our server metrics. We have not seen a spike in memory usage. If garbage collection was causing a performance slow down would we see a spike in memory usage ? Is this a sign that the performance issues are being caused elsewhere ? Possible by gems not playing nicely together ?

RubyOnRails- How to bundle?

Posted: 01 Jun 2016 05:25 AM PDT

I am trying to install all dependencies via following command:

bundle install  

It gave me following error:

An error occurred while installing libv8 <3.16.14.13>, and bundle cannot continue.  Make sure  that 'gem install libv8 -v '3.16.14.13' ' succeeds before bundling.  

Then from this link:

rails gem install ERROR: Error installing libv8: ERROR: Failed to build gem native extension

I found this solution:

gem install libv8 -v '3.16.14.13' -- --with-system-v8  

It then installed the libv8

Then again I ran the command:

bundle install  

Now its giving me following error:

An error occurred while installing therubyracer <0.12.2>, and bundler cannot continue.  Make sure that 'gem install therubyracer -v '0.12.2' ' succeeds before bundling.  

I tried deleting therubyracer from gem file and then run the command but i am getting the same error.

Please guide me.

Thanx

Rails Gem "Axlsx" - Rename Workbook

Posted: 01 Jun 2016 06:06 AM PDT

My workbook always named like my template "invoices_generate.xlsx". How can i rename this File ?

Template "invoices_generate.xlsx.axlsx" :

wb = xlsx_package.workbook        wb.add_worksheet(:name => "Beleg") do |sheet|          .      .      .        sheet.column_widths 2 , 11, 11, 11, 11, 23, 3        end  

Rails Arel complex query

Posted: 01 Jun 2016 04:46 AM PDT

I am trying to combine an arel query with a Product scope.

p  = Spree::Product.arel_table  p1 = Spree::ProductProperties.arel_table  p2 = p1.alias  query = p   .join(p1)     .on(p[:id].eq(p1[:product_id]))       .where(p1[:property_id].eq(5)         .and(p1[:value].eq("10 inches")))   .join(p2)     .on(p[:id].eq(p2[:product_id]))       .where(p2[:property_id].eq(4)         .and(p2[:value].eq("1400")))  

Now the problem is that this results in error when I try to combine it with base_scope thats adds some other criteria. base_scope.where(query)

=> "SELECT \"spree_products\".* FROM \"spree_products\" WHERE \"spree_products\".\"deleted_at\" IS NULL AND ((SELECT FROM \"spree_products\" INNER JOIN \"spree_product_prop erties\" ON \"spree_products\".\"id\" = \"spree_product_properties\".\"product_id\" INNER JOIN \"spree_product_properties\" \"spree_product_properties_2\" ON \"spree_product s\".\"id\" = \"spree_product_properties_2\".\"product_id\" WHERE \"spree_product_properties\".\"property_id\" = 5 AND \"spree_product_properties\".\"value\" = '10 inches' AN D \"spree_product_properties_2\".\"property_id\" = 4 AND \"spree_product_properties_2\".\"value\" = '1400'))"

Is there a way to achieve that wihout going to plain sql?

Rails4 form dynamic read only field

Posted: 01 Jun 2016 05:20 AM PDT

I have a rails form that needs at field to be readonly or not depending on the checkbox the user clicks. So far I have

<%= form_for @weight, remote: true do |f| %>    <div class= "modal-body">       <input id="checkbox1" type="checkbox" onclick="ReadOnly()"></input>       <%= f.label :weight_number, class="control-label"%>       <%= f.number_field :weight_number, :readonly => true, class="form-control"%>    </div>  <% end %>   <script>      function ReadOnly(){        if(document.getElementById('checkbox1').checked{           //make the number field editable        }      }   </script>  

Is there a clean and concise why do this. I've never had to manipulate a ruby line via JavaScript before, but I would like to toggle that numbe field between :readonly => true and :readonly => false.

How can i add tooltip to action item in my index page of active admin

Posted: 01 Jun 2016 04:53 AM PDT

In my app's admin portal i added action item , on its click new resource opened. I want to add tooltip to it , to clarify where does this button take. How can i add tooltip in active admin.

Below is the code where i define an actionitem , i want to add tooltip here to give some information about this action item.

action_item  only: :index  do      def permitted_params       params.permit(:q => [:gender_eq , :date_of_birth_gteq , :date_of_birth_lteq , :relationship_status_id_eq,:occupation_id_eq, :qualification_id_eq ,:monthly_income_id_eq ,:common_interests_interest_id_eq , :location_id_eq, :number_of_people_at_home_eq ,:area_eq, :transport_id_eq , :like_count_in , :view_count_in , :view_greater_in   , :like_greater_in])    end      if !params[:q].nil?         filter_user=User.search(params[:q])         if filter_user.result.count > 0          p=PsychographicsFilter.create(permitted_params["q"])          session[:last_update]=p.id          session[:associated_user_ids]=filter_user.result.map(&:id)          link_to "Ask Question",  new_admin_psychographics_question_path(:post => { :filter_id => session[:last_update] , :users => session[:associated_user_ids]})          end      end  

end

First request to rails app extremely slow

Posted: 01 Jun 2016 04:27 AM PDT

The first request to my rails app is extremely slow in all environments.

This should not be due different way of caching/loading gems. It was fine two hours ago and no major changes are made.

What I did the hours before I noticed my app turned slow:

  • I messed around in production.rb (NOT in development.rb): I was playing around with config.serve_static_assets = true

  • I did a bunch of tasks to diagnose why asset pipeline did not load my stylesheets and images in production (like rake assets:precompile RAILS_ENV=production and rake:clean assets:precompile).

Afterwards I obviously tried to undo all the changes I made, but for some reason my app is now slow in development, while it was perfectly fine before.

Thanks in advance :-)

UPDATE 1

When I send a request for localhost:3000, only after 12-13 seconds I receive: Started GET "/" for ::1 at random time

Rendering behaving is normal. All requests after the first one are fine.

Devise login doesn't work / no error messages

Posted: 01 Jun 2016 05:30 AM PDT

Guys i've looked everywhere to fix this issue but I'm out of luck.

I got a devise login system and i signed up an account admin@admin.com in development and on the log i got the confirmation email and i went to that email and so my account got confirmed. Now when i try to login the console gives me this message:

Started GET "/users/sign_in?utf8=%E2%9C%93&authenticity_token=iHIEXxGHWaIdtAGhcZ7EKvEEEYGmoEfgr1K8NcKb9nFIXuD6dpMVimOO6aBEdZJUWv9Irt%2FT0vnaucjW%2BgmJQQ%3D%3D&user%5Bemail%5D=admin%40admin.com&user%5Bpassword%5D=[FILTERED]&user%5Bremember_me%5D=0&commit=Log+in" for ::1 at 2016-06-01 13:11:54 +0200  Processing by Devise::SessionsController#new as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"iHIEXxGHWaIdtAGhcZ7EKvEEEYGmoEfgr1K8NcKb9nFIXuD6dpMVimOO6aBEdZJUWv9Irt/T0vnaucjW+gmJQQ==", "user"=>{"email"=>"admin@admin.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}    Rendered devise/sessions/new.html.erb within layouts/application (3.7ms)    Rendered partials/_header.html.erb (0.5ms)    Rendered partials/_menu.html.erb (0.2ms)    Rendered shared/_breadcrumbs.html.erb (0.0ms)    Rendered partials/_footer.html.erb (0.0ms)    Rendered partials/_javascripts.html.erb (0.0ms)  Completed 200 OK in 143ms (Views: 52.6ms | ActiveRecord: 0.0ms)  

After this the page just refreshes and i'm not logged in. When i go to resend confirmation instructions it says 'email is already confirmed, try signing in'

My sign in form looks like this:

<% provide(:title, "Sign in") %>  <div class="col-md-12">    <form class="sign-box">      <header class="sign-title"> Sign in </header>        <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>            <% if devise_error_messages!.present? %>              <div class="alert alert-warning alert-icon alert-close alert-dismissable fade in" role="alert">                <button type="button" class="close" data-dismiss="alert" aria-label="Close">                  <span aria-hidden="true">&times;</span>                </button>                <i class="font-icon font-icon-warning"></i>                <%= devise_error_messages! %>              </div>          <% end %>          <div class="field form-group">          <%= f.label :email, class: 'float-left' %><br />          <%= f.email_field :email, class: 'form-control', autofocus: true %>        </div>          <div class="field form-group">          <%= f.label :password, class: 'float-left' %><%= link_to 'Forgot your password?', new_user_password_path, class: 'float-right reset' %>          <%= f.password_field :password, class: 'form-control', autocomplete: "off" %>        </div>          <% if devise_mapping.rememberable? -%>          <div class="field form-group">            <div class="checkbox float-left">              <%= f.check_box :remember_me %>              <%= f.label :remember_me %>            </div>          </div>        <% end -%>          <div class="actions">          <%= f.submit "Log in", class: 'btn btn-rounded' %>        </div>            <p class="sign-note">New to our website? <%= link_to "Sign Up", new_user_registration_path %></p>      <% end %>    </form>  </div>  

What could it be guys? I'm out of options after trying for days.

How to set multiple parents inside Rails Devise configuration?

Posted: 01 Jun 2016 03:59 AM PDT

By default the devise inherited controllers will have application_controller as parent, and we can change the parent controller to "ApiBaseController" by following way:

# config/initializers/devise.rb  # Now Devise inherited controllers will pass through Api::ApiBaseController  config.parent_controller = 'ApiBaseController'  

I need some Devise inherited controllers pass through ApiBaseController, while some other Devise inherited controllers need to pass through PublicBaseController, and few others as ApplicationController, etc. But we can set one parent at a time for one Rails Application by following way.

config.parent_controller = 'ApiBaseController'  

Any help would be appreciated.

Rails, fields_for generate fields for as many attachments (even 0), while I want only/at least one

Posted: 01 Jun 2016 06:38 AM PDT

I have areas and every area has multiple images through area_attachments.

I have a modal to edit each area.

I also want to edit area_attachments in each area so I have a f.fields_for in every area form.

<%first_rendered=false %>  <%= f.fields_for :area_attachments do |aa| %>    <%unless first_rendered %>    <div class="field">     <br>     <%= aa.file_field :image, :multiple => true, name: "area_attachments[image][]" %>    </div>    <% first_rendered=true %>    <% end %>  <% end %>  

Because it is multiple upload I only want one field so the user can upload more images to an area.

As you can see I have a first_rendered variable, so if an area has more than one area_attachments the field will only show once, there is no reason for more fields.

But if an area has no area_attachments at all, the field will not show up at all.

What would you suggest I do here? Also, would you do something else instead of this first_rendered variable I used? Generally, how would you do it so only one field is generated?

Multi table Inheritance on rails (active record)

Posted: 01 Jun 2016 06:40 AM PDT

I am trying implement a Multi table Inheritance. In my situation I am trying modeling Appliances. Appliances have common attributes like price, name and model but there are different types of appliances like TV, Freezer, Fridge with different attributes (temperature, size, etc...).

I search and I found this gem https://github.com/hzamani/active_record-acts_as. What you think ? What is the best way to implement this ? There is other pattern to implement this ?

1 comment:

  1. awesome post presented by you..your writing style is fabulous and keep update with your blogs
    Ruby on Rails Online Training Bangalore

    ReplyDelete