Thursday, July 7, 2016

With ruby on rails and devise, how to create another model instance belonging to a user that has just registered (i.e. for the first time)? | Fixed issues

With ruby on rails and devise, how to create another model instance belonging to a user that has just registered (i.e. for the first time)? | Fixed issues


With ruby on rails and devise, how to create another model instance belonging to a user that has just registered (i.e. for the first time)?

Posted: 07 Jul 2016 08:01 AM PDT

I've been looking a few hours in order to find best practices to the following problem: each time a new user registers on my app (with devise), I want to create 3 default Wishlists that will belong to this new user so that he/she can fill them in later on.

class User < ActiveRecord::Base    has_many :wishlists, dependent: :destroy  end    class Wishlist < ActiveRecord::Base    belongs_to :user  end

I have read some posts on apparently similar topics but never satisfying my need, which was, in particular, to not modify the registration form and to get the user_id in order to properly create the associated wishlists.

So here is the solution I finally used (below as an answer), should someone have the same issue.

Do better practices exist? Happy to read your thoughts.

Salesforce disabling TLS 1.0

Posted: 07 Jul 2016 07:57 AM PDT

I am working on a salesforce application which is hitting an API built using ruby on rails. Initially this application was working fine until I faced errors while deploying the application using Jenkins. I checked the logs and it mentions "Stronger security is required, To access this website, update your web browser or upgrade your operating system to support TLS 1.1 or TLS 1.2. Salesforce disabling TLS 1.0".

What can i alter within my ROR application to resolve this error. I have already tried adding openssl gem to my gemfile but the issue still persists. Here is the error log:

<table width="100%" height="100%" border="0">  <tr><td width="100%" height="100%"><div class="content"><h1>Stronger security is required</h1><div class="simple"><p>To access this website, update your web browser or upgrade your operating system to support TLS 1.1 or TLS 1.2.</p><p>For more information, see <a href="https://help.salesforce.com/HTViewSolution?id=000221207&amp;language=en_US" target="_blank">Salesforce disabling TLS 1.0</a>.  </p></div></div></td></tr>  </table  

What other guard-gems am I missing in my rails project that could help me?

Posted: 07 Jul 2016 07:58 AM PDT

In my Rails 3.2 project I have a Gemfile with:

group :development do    gem 'guard'    gem 'guard-bundler', require: false    gem 'guard-livereload'    gem 'rack-livereload'    gem 'guard-annotate'    ...  end    group :development, :test do    gem 'rspec-rails'    gem 'capybara', git: 'git://github.com/jnicklas/capybara.git'    gem 'launchy'    gem 'database_cleaner'    gem 'rb-fsevent', require: false if RUBY_PLATFORM =~ /darwin/i    gem 'guard-rspec'  end  

I have tried some other guard gems. I am infatuated with guard at the moment and don't want to miss any guard goodness. Are there any guard gems that have been helpful to you that I have missed?

There is a long list here, but I'm particularly interested in what your experience can teach me.

I should have known I would get a 'drive by' down vote or two. If you don't like the question, please demonstrate some integrity by adding a comment that indicates why.

Thanks!

execution expired exception when using actionmailer rails 4

Posted: 07 Jul 2016 07:20 AM PDT

I used actionmailer in two ways. First one with gmail smtp with configuration:-

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }    config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true    config.action_mailer.raise_delivery_errors = true    config.action_mailer.default :charset => "utf-8"    ActionMailer::Base.delivery_method = :smtp # be sure to choose SMTP delivery    ActionMailer::Base.smtp_settings = {      :address              => "smtp.gmail.com",      :port                 => "587",      :domain               => "gmail.com",      :user_name            => "some-username@gmail.com",      :password             => "some-password",      :authentication       => "plain",      :enable_starttls_auto => true    }  

That works very fine. The mail was sent.

The issue is when I decide to use my mail server in my server with configuration:-

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }    config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true    config.action_mailer.raise_delivery_errors = true    config.action_mailer.default :charset => "utf-8"    ActionMailer::Base.delivery_method = :smtp # be sure to choose SMTP delivery    ActionMailer::Base.smtp_settings = {      :address              => "mail.xgram.xyz",      :port                 => "25",      :domain               => "xgram.xyz",      :user_name            => "some-username@xgram.xyz",      :password             => "some-password",      :authentication       => "plain",      :enable_starttls_auto => true    }  

With this configuration, I got this error in terminal

Net::OpenTimeout (execution expired):

and this error in the browser

execution expired

In addition, mail.xgram.xyz as server name is valid, because when I change it to any arbitrary name, The error will be

getaddrinfo: Name or service not known

Can any one help me ? Thank you in advance

How to customize devise reset password template?

Posted: 07 Jul 2016 07:48 AM PDT

I want to use the default template to send reset password mail. I generate devise views and restart the server, but still failed with undefined method 'edit_password_url'

reset_password_instruction.html.erb

<p><%= t(:hello).capitalize %> <%= @resource.email %>!</p>    <p><%= t '.request_reset_link_msg' %></p>    <p><%= link_to t('.password_change_link'), edit_password_url(@resource, reset_password_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s).html_safe %></p>    <p><%= t '.ignore_mail_msg' %></p>  <p><%= t '.no_changes_msg' %></p>  

What's wrong?

simple remotipart alternative using async file upload instead of iframe trick?

Posted: 07 Jul 2016 06:53 AM PDT

I was using remotipart to get "remote: true" forms to upload images (using paperclip) and was working fine. However, we now have an iOS "App" that is just our website wrapped in a webview, and file uploads do not work here. I believe it has something to do with the webview mucking with iframes but not sure and we don't have access to the iOS code (it was from a thirdparty company). I found that jquery-file-uploader does work in the app since it uses async xhr file uploads, but there is no simple integration for this like remotipart where you can just drop it in and have all your "remote: true" forms start working. Is there any gem out there that does this? With jquery-fileupload-rails gem I have to do this to get the same functionality:

  1. Disable automatic upload
  2. Set the form to "remote: false", then override the form submit button (preventDefault) and call data.submit() manually, but only if the user chooses to upload an image, if not I let the default form action work.
  3. Handle validation error in the controller. If there is an error (like blank field) The image is not saved, but the path to the image is changed and when the form is reloaded with validation errors the image shows as missing instead of the original image, so I have to manually replace the image with the original in the controller in case of error. Also, ideally it would keep the file they specified instead of resetting the field, but not sure how to do this yet, so even if there is an error in another field, they have to re-select their file.

I have a complex form with several nested fields (that also accept image uploads) and also and "attachments" section that has dynamically added file fields. These dynamically added fields do not get picked up with the original call to .fileupload() when the form loads, so I have to call it again for each added file field, however this seems to not be working right now and causes the other images to not get uploaded...

Anyway, was wondering if there was an equivalent to remotipart that is a drop in fix for remote forms that uses xhr instead of iframe....

Couldn't find Job with 'id'=:27

Posted: 07 Jul 2016 06:55 AM PDT

I am doing a query for

 @job = Job.find(params[:id])  

the URL is http://localhost:3000/jobs/:27

so the params for the job id are in the url, and I know the job 27 exists. it works fine when I search

@job = Job.find(27)  

so I think it is the colon that is causing the error. but its should work. It's driving me nuts. Is there a way to get rid of the colon or is there something simple I should be dong?

How should I have debugged this?

Posted: 07 Jul 2016 05:58 AM PDT

I was going through this DHH video on using Web Sockets with Action Cable. https://www.youtube.com/watch?v=n0WUjGkDFS0. When I got to the end it had functionality EXCEPT what I entered in the text box was not appearing on the screen until I performed a page refresh.

I went through the video and found I had a typo. Around 18 minutes in the video DHH is in message_broadcast_job.rb and on this line:

ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })  

I had local instead of locals. Changed it and it worked.

But how would I have gone about actually debugging this? Should I have used pry? And if so how?

Or something else?

Find records with ids and keep the same order as in ids array [duplicate]

Posted: 07 Jul 2016 06:16 AM PDT

This question already has an answer here:

I have ids array ids = [5,2,1,6].

I'd like to find all records with these ids and keep the same order as in the ids array.

Regular records = Product.find(ids) does not keep this order(not sure, but probably it sorts by id).

Can't get correct result from my if !=nil statement

Posted: 07 Jul 2016 07:27 AM PDT

Beginner alert!
I have this IF statement in my user#show view. I checked if any post for user_id:7 in rails console, it returns the result nil, but when I looked at http://localhost:3000/users/7, I can't see the comment:

You don't have any post yet. Keep posting!

<% @posts.each do |post| %>  <% if @posts != nil %>  <%= link_to "#{post.title}", post_path(post) %>  <% else %>  <p> You don't have any post yet. Keep posting! </p>  <% end %>  <% end %>  

Could anyone help me? Thanks!

Can't find lodash.pull function for Ruby array

Posted: 07 Jul 2016 05:46 AM PDT

Is there any utility function which works like lodash.pull but for Ruby arrays?

Rails Asset Pipeline URLs

Posted: 07 Jul 2016 05:33 AM PDT

In Rails, the asset pipeline concats all your assets (images, css, js and fonts) and loads them from an assets folder.

First question... where does this assets folder that the files are loaded from compressed exist? As it's not the one that lives in app/assets as that's the originals.

Secondly, after compression the files are loaded directly from the assets folder at the same level... so images are with css and js, etc. Is it possible to change this so that the subfolders are kept intact?

So turn

/assets/logo-ffbd470b80efb31e6e852d938c4e3db30fda9dfd1b6f07a0ed36449f1ac9febc.png

to

/assets/images/header/logo-ffbd470b80efb31e6e852d938c4e3db30fda9dfd1b6f07a0ed36449f1ac9febc.png

Before Action Authenticate with Devise and STI not working

Posted: 07 Jul 2016 06:36 AM PDT

I'm trying to use before_action :authenticate_admin! to determine if the current user is an admin or not. I am using devise with single table inheritance (STI).

Here is my User model;

class User < ApplicationRecord    def admin?      false    end    devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :lockable  end  

And my Admin model;

class Users::Admin < User    def devise_scope      :admin    end      def admin?      true    end  end  

Just to test out devise, I have this in my routes file;

authenticated :user, ->(u) { u.admin? } do    resources :teams  end  

And indeed, if I am signed in as a different User type (so not Admin), I can't get to that resource.

But this fails to work;

class Teams < ApplicationController    before_action :authenticate_admin!      def index      end  end  

I get the error;

undefined method `authenticate_admin!'

Quite new to Rails so I don't understand how to resolve this.

UPDATE

I had to put this in the routes file;

devise_for :admins, class_name: 'Users::Admin'  

Previously I only had;

devise_for :users, controllers: {sessions: 'users/sessions'}  

How to run rails background jobs in a sequential manner?

Posted: 07 Jul 2016 05:00 AM PDT

I am calling a background job from my controller to fetch around 1000 entries from the database and work on it. However I want to call this job for every new entry in the database. How can I execute this in a sequential manner? As in, if one entry is executing the job, other one should wait for it and then perform the task.

Rails, Passenger, nginx, how to configure a simple SSL?

Posted: 07 Jul 2016 05:43 AM PDT

I am a beginner in rails and web development. I am trying to make my online website from HTTP to HTTPS. Everything looks so complicated, I can't find a beginner-friendly guide. I used the openssl to generate my keys but how should I use them? Should I add them to my nginx.conf and that's it?

Any links or tips would be greatly appreciated.

Not receiving mails with Rails actionmailer and delayed job

Posted: 07 Jul 2016 07:43 AM PDT

I am using delayed job with actionmailer. I have more than 5 mailer and 40 mailer actions. All working fine except for one mail action mails are not being send or not being received by user for some user. But when I try with disabling delayed_job, its working perfectly. I checked the logs, one job is created every time and processed without error. I even have configuration to not to remove failed jobs. I don't know if I should post any code here since with delayed job disabled, that mail is working fine so I guess issue is not with mailer action. I can't figure it out that where is the problem.

Edit (log for failing job):

D, [2016-07-07T05:53:00.757530 #31786] DEBUG -- : User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 69 LIMIT 1 D, [2016-07-07T05:53:00.773829 #31786] DEBUG -- : EquipmentMailer#send_post_expired_email: processed outbound mail in 190.1ms D, [2016-07-07T05:53:00.774358 #31786] DEBUG -- : (0.1ms) BEGIN D, [2016-07-07T05:53:00.775255 #31786] DEBUG -- : SQL (0.3ms) DELETE FROM `delayed_jobs` WHERE `delayed_jobs`.`id` = 255 D, [2016-07-07T05:53:00.776992 #31786] DEBUG -- : (1.6ms) COMMIT I, [2016-07-07T05:53:00.777182 #31786] INFO -- : 2016-07-07T05:53:00-0700: [Worker(delayed_job host:example.com pid:31786)] Job EquipmentMailer.send_post_expired_email (id=255) COMPLETED after 0.1972

I noticed that immediately after processing the outbound mail, it is deleting job but for working jobs it after processing it creates the mail with from, to, render the template and encode the assets.

How to show form results even when pressing the back button

Posted: 07 Jul 2016 04:56 AM PDT

I have a form which a user selects a location. It has remote: true on it and its setup so i can bring results back in an ajax way.

form

<%= form_for :location, url: get_inventory_path, remote: true do |f| %>              <div class="input-field col s12">                <%= f.select :location_id, options_for_select(@locations.collect { |l|                  [l.station + ', ' + l.venue + ', ' + l.area + ', ' + l.city + ', ' + l.country, l.id] }, 1), {}, { id: 'location_select', class: "browser-default" } %>              </div>          </div>        </div>        <div class="card-action center-align">          <%= f.submit "Go", class: "btn blue", data: { disable_with: "Please wait..." } %>        </div>        <% end %>  

The thing is, on the results i have some buttons to edit those results, which takes the user to another page, but on pressing the back button the form results are not there.

How can i show those results, or remember them somehow?

Polymorphic model and has_many through

Posted: 07 Jul 2016 05:35 AM PDT

I have a polymorphic model Document and multiple models with documents linked. One of which the CustomerPlan model that has_many documents, as: :linkable. This works fine.

In addition I have a Company model that has_many :customer_plans. As such an instance of Company should also have many documents. How do I properly set up the has_many relation between the Company model and the Document model?

Currently:

Schema:

  create_table "documents", force: :cascade do |t|      t.json     "links"      t.integer  "linkable_id"      t.string   "linkable_type"      t.datetime "created_at"      t.datetime "updated_at"    end      add_index "documents", ["linkable_type", "linkable_id"], name: "index_documents_on_linkable_type_and_linkable_id", using: :btree  

Models:

class Document < ActiveRecord::Base    belongs_to :linkable, polymorphic: true    belongs_to :user    belongs_to :company      mount_uploaders :links, DocUploader  end        class CustomerPlan < ActiveRecord::Base    belongs_to :company    has_many :documents, as: :linkable    accepts_nested_attributes_for :documents  end    class Company < ActiveRecord::Base    has_many :customer_plans    has_many :documents  end  

will_paginate's per_page limit not working

Posted: 07 Jul 2016 06:22 AM PDT

I can't figure out why the :per_page limit does not work for surf_school_reviews. It still shows all the reviews although I set the :per_page limit (I just set it to 2 so that I won't have to create many reviews just to test if it works). I am confident that all my associations and codes are correct as shown below. But I have not encountered any problems when will_page is used for surf_schools.

I am sorry if my description is not clear, so you can just comment and clarify so that I can explain it further to you.

surf_schools_controller.rb

def show   @surf_school = SurfSchool.find(params[:id])   @surf_school_reviews = @surf_school.surf_school_reviews.paginate(page: params[:page], per_page: 2)  end  

surf_school.rb

belongs_to :user  has_many   :surf_school_reviews  

surf_school_review.rb

belongs_to :surf_school  belongs_to :user  

user.rb

has_many :surf_schools,        dependent: :destroy  has_many :surf_school_reviews, dependent: :destroy  

routes.rb

resources :surf_schools do   resources :surf_school_reviews, except: [:index, :show]  end  

Convert group count from activerecord into hash with multiple group stages

Posted: 07 Jul 2016 05:38 AM PDT

I'm trying to get some statistics.

Model.where(status:@statuses).group(:sub_group, :status).count  

This returns me

{    ["sub_group1", "status1"] => 3},    ["sub_group2", "status3"] => 7,    ["sub_group1", "status2"] => 5, ....etc }  

I want to merge them so each element has a unique subgroup.

e.g. a hash like:

{    "sub_group1" => {"status1" => 3, "status2" => 5,    "sub_group2" => {"status3" => 7},  }  

or an array

[    ["subgroup1", {"status1" = 3, "status2" => 5}],    ["subgroup2".....    ]  

i.e. I want all those terms to be merged with sub_group as the primary header so that I can get the results for subgroup in one item.

Brain not working today....

Specify the git branch code to be deployed in Elastic Beanstalk environment

Posted: 07 Jul 2016 03:51 AM PDT

Is there any way to specify which git branch code to be deployed to an Elastic Beanstalk environment?

Assume, I have two git branches named test and stage and I have an Elastic Beanstalk environment named test-env.

Now, I set the branch defaults in config.yml as below:

branch-defaults:     test:      environment: test-env      group_suffix: null  global:    application_name: test    default_ec2_keyname: abcde    default_platform: Ruby 2.2 (Puma)    default_region: us-west-2    profile: eb-cli    sc: git  

Now, what I need is if I deploy from stage branch with eb deploy test-env it should automatically deploy the code from test branch or it should throw an error..

Is there any way to do it. If no please suggest me some other way to do it..

Thanks..

How to show error message in model

Posted: 07 Jul 2016 03:48 AM PDT

Hello I am using before_update callback and my requirement is to show error message in this.

Spree::Order.class_eval do    before_update :check_email, if: :email?    def check_email      if Spree::User.where(:email => self.email).present? && self.user.blank?        self.errors.add(:base,  message: Spree.t(:user_email_present))        return false      end    end  end  

but when it returns to page it do not show given error message. Please guide me how to show error message or flash with rails model.

How to setup a RoR application with SSO on Azure AD

Posted: 07 Jul 2016 03:02 AM PDT

I am struggling to setup a Ruby on Rails, ActiveAdmin application which uses Devise for authentication. I am using the Azure AD strategy for the omniauth strategy.

I have added omniauth strategy in config/initializers/devise.rb:

config.omniauth :azure_activedirectory, 'app id', 'azure tenant id'  

Added the Users::OmniauthCallbacksContoller:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController    def azure_activedirectory      @user = AdminUser.from_omniauth(request.env['omniauth.auth'])        if @user.persisted?        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated        set_flash_message(:notice, :success, :kind => 'azure_activedirectory') if is_navigational_format?      else        session['devise.azure_activedirectory_data'] = request.env['omniauth.auth']        redirect_to new_admin_user_registration_url      end    end      def failure      redirect_to root_path    end  end  

And added the callback routes to routes.rb:

Rails.application.routes.draw do    devise_config = ActiveAdmin::Devise.config    devise_config[:controllers][:omniauth_callbacks] = 'users/omniauth_callbacks'    devise_for :admin_users, devise_config      devise_scope :admin_user do      get 'sign_in', :to => 'devise/sign_in', as: :new_admin_user_session      get 'sign_out', :to => 'devise/sign_out', :as => :destroy_admin_user_session    end      ActiveAdmin.routes(self)      root to: redirect('/admin')  end  

Added the from_omniauth method to models/admin_user:

class AdminUser < ActiveRecord::Base    devise :trackable, :omniauthable, omniauth_providers: [:azure_activedirectory]      def self.from_omniauth(auth)      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|        user.email = auth.info.email        user.password = Devise.friendly_token[0,20]      end    end  end  

But all I get when I run the application is the error: The action 'sign_in' could not be found for Users::OmniauthCallbacksController

I am at an end now, I do not know what else I have to do to get it working. https://github.com/AzureAD/omniauth-azure-activedirectory and https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview do not show any leads for me anymore on how to fix it.

Can anybody help me on what I do wrong?

A value in a form_for field

Posted: 07 Jul 2016 03:17 AM PDT

I'm trying to set a value for a form field like this:

<%= form_for (@change_office_address), remote: true, format: :json, html: { class: :contact_form } do |f| %>    <%= f.text_field :city_id, class: 'form-control', value: @office.city.id, disabled: true %>     <%= f.submit, class: 'btn btn-default' %>  <% end %>  

In a view I can see the id in a field, but when I tried to submit the form, I see that validation doesn't pass. The validation looks like this:

class ChangeOfficeAddress < ApplicationRecord    belongs_to :city    validates :city_id, presence: true  end  

In my schema the column city_id is set to integer. I also tried to change f.text_field to f.number_field, but it didn't help either. So, what can be wrong? Thanks ahead.

Rails 4: building a super simple api method and securing it

Posted: 07 Jul 2016 03:55 AM PDT

Hi guys what will be the best way to add one method in controller that will be exposed as an api to be used by another application (only one) to update some columns in database? I don't want to build a fancy api with versioning and all, it will be simple one method in controller exposed as api responding with json data. Also, how should I go about securing it?

Tech stack: rails 4, json

cannot load such file -- map_fields

Posted: 07 Jul 2016 02:37 AM PDT

In my Rails 3.2.13 application, there is an import contact page where we can import contacts through csv and if any fields or mapping missing, we can manually map with headers. For this they have used map_fields plugin where most of the code consists in public -> plugins folder. Now when I try to run the same in 4.2.6 application, this is the error I am facing:

LoadError - cannot load such file -- map_fields: activesupport (4.2.6) lib/active_support/dependencies.rb:274:in block in require'
activesupport (4.2.6) lib/active_support/dependencies.rb:238:in
block in load_dependency' activesupport (4.2.6) lib/active_support/dependencies.rb:647:in new_constants_in'
activesupport (4.2.6) lib/active_support/dependencies.rb:238:in
load_dependency' activesupport (4.2.6) lib/active_support/dependencies.rb:274:in require'
app/controllers/contacts_controller.rb:2:in
'
app/controllers/contacts_controller.rb:1:in <top (required)>'
activesupport (4.2.6) lib/active_support/dependencies.rb:457:in
block in load_file' activesupport (4.2.6) lib/active_support/dependencies.rb:647:in new_constants_in'
activesupport (4.2.6) lib/active_support/dependencies.rb:456:in
load_file' activesupport (4.2.6) lib/active_support/dependencies.rb:354:in require_or_load'
activesupport (4.2.6) lib/active_support/dependencies.rb:494:in
load_missing_constant' activesupport (4.2.6) lib/active_support/dependencies.rb:184:in `const_missing'

This is my controller:

class ContactsController < ApplicationController    require 'map_fields'    map_fields :mapper, ['First Name','Last Name', 'Email', 'Notes'], :file_field => :file, :params => [:contact]      def create      @user = User.find(params[:user_id])      @contact = @user.contacts.create(contact_params)      respond_to do |format|        if @contact.save          format.json { render :json => { :notice => 'Contact was successfully created!',:redirect => user_contacts_url} }          format.html { redirect_to(user_contacts_url(@user), :notice => 'Contact was successfully created!', :type => 'success') }         else          format.json { render :json => {:redirect => false} }          format.html { render :action => "edit" }        end      end    end    def import      @contact = Contact.new     end      def mapper      @contact = Contact.new(params[:contact])      count = 0        if fields_mapped?        mapped_fields.each do |row|          params[:contact] = {"user_id" => @current_user.id, "firstname" => row[0], "lastname" => row[1], "notes" => row[3], "email" => row[2].try(:strip)}          contact = Contact.new(params[:contact])            if contact.save            count = count + 1          end        end          if count > 0          flash[:notice] = "#{count} Contact(s) created"          redirect_to :action => :index        else           flash[:notice] = "No contact was created..."           redirect_to :action => :index        end        else        @best_row = @rows[1]        render      end        rescue MapFields::InconsistentStateError        flash[:error] = 'Please try again'        redirect_to :action => :import      rescue MapFields::MissingFileContentsError        flash[:error] = 'Please upload a file'        redirect_to :action => :import    end    end  

Other than this I am having contacts/import.html.erb:

<%= semantic_form_for :contact, :url => mapper_user_contacts_path do |f| %>     <%= f.inputs :name => 'Please select a CSV file to upload' do %>       <%= f.input :file, :label => false, :as => :file, :input_html => {:name => "file", :id => "file"} %>     <% end %>     <%= f.buttons do %>       <%= f.commit_button raw('Import contacts') %>     <% end %>    <% end %>  

and app/views/contacts/mapper.html.erb:

<%= render :partial => 'map_fields/map_fields' %>  

The above render fields are in vendor -> plugins -> map_fields folder.

Please help me how can I overcome the error? Is data rendered from plugin folder?

Make partials in a controller

Posted: 07 Jul 2016 03:16 AM PDT

I'm building a ruby on rails app and I have rather big controllers.

Now I have the same actions to be done on a create action and a delete action so I was wandering if it's possible to make this DRY. Or is this only possible with views?

"\xFF" from ASCII-8BIT to UTF-8 using paperclip

Posted: 07 Jul 2016 02:32 AM PDT

I got a problem using paperclip gem in rails. I was following this tutorial https://devcenter.heroku.com/articles/paperclip-s3 I got this param in my avatar ActionDispatch::Http::UploadedFile:0x007f5f2bdafde0 that give me this error when i'm using json: "\xFF" from ASCII-8BIT to UTF-8 So anyone know what i have to do with this param ? I try to force encode it but it's not working any ideas?

I m using s3 amazon service for upload my avatar.

gem install nokogiri -v '1.5.11' failed due to make: /usr/local/bin/gmkdir: No such file or directory

Posted: 07 Jul 2016 02:28 AM PDT

Ruby version: 2.2.5

Mac OSX: 10.11.5

Gem version: 2.4.8

Bundler version: 1.12.5

When I run gem install nokogiri -v '1.5.11', I got the following error:

Building native extensions. This could take a while...  ERROR:  Error installing nokogiri:  ERROR: Failed to build gem native extension.    /Users/hwpeng/.rvm/rubies/ruby-2.2.5/bin/ruby -r ./siteconf20160707-31800-1ejznjc.rb extconf.rb    ====ignored multiple lines====    make "DESTDIR=" install  make: /usr/local/bin/gmkdir: No such file or directory  make: *** [.RUBYARCHDIR.-.nokogiri.time] Error 1    make install failed, exit code 2  

Ruby on Rails header for sending files In NGINX

Posted: 07 Jul 2016 05:05 AM PDT

My application runs on a Nginx and passenger server. Inside the production.rb I see a line says:

# Specifies the header that your server uses for sending files.  config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX  

How does it Specifies header to sending files? How does Rails sends file without having this turned on?

Is it a good practice so turn this on? Does it make my application to run faster?

No comments:

Post a Comment