Wednesday, July 27, 2016

Managing access to a file with a direct link | Fixed issues

Managing access to a file with a direct link | Fixed issues


Managing access to a file with a direct link

Posted: 27 Jul 2016 07:41 AM PDT

I have a rails app where I upload files. I'm using gem cancan for managing access to files. The files are stored on the disk. Is it possible to manage access to a file or restrict/allow it even when a user has a direct link to it? Note I'm not using nginx or apache, it's a local application, therefore at best it's unicorn or simply the standard Rails web server.

extract and convert any ascii code from a string

Posted: 27 Jul 2016 07:42 AM PDT

How can I extract the ascii code from a string and then convert it to char?

string = "a – b"

to

a – b

rails How to calculate time difference with integer between 3 dates

Posted: 27 Jul 2016 07:38 AM PDT

How to compare 3 dates, (Time.now - @model.updated_at) < :integer(converted to days) , So first is a substraction between two dates and the difference between the two dates as (amount of time) is compared(< less than) to an :integer.days(amount of time). Hope this makes sense... im going through different options but im just getting more confused. Thanks for any help.

"#{Time.now}".to_i.days - "#{:updated_at}".to_i.days < "#{:integer}".to_i.days  

Check if SVG exists in Rails

Posted: 27 Jul 2016 07:16 AM PDT

I have the following code as a helper that I want to use to check if an image exists and if so then return it's raw SVG data:

def svg(name: 'default')    file = asset_path('images/' + name + '.svg')    if( File.file?(file) )      file = File.open(file, 'rb')      contents = file.read      file.close      contents.html_safe    end  end  

However the file always comes back false... (the svg exists!)

Is the way I'm getting the file incorrect?

Unable to create model based forms rails 4

Posted: 27 Jul 2016 07:03 AM PDT

I have model based form:

<h2>Add New Credit Card</h2>  <%= form_for @credit_card do |f| %>       some fields  <% end %>  

routes:

resources :credit_card    credit_card_index GET    /credit_card(.:format)                       credit_card#index                       POST   /credit_card(.:format)                       credit_card#create       new_credit_card GET    /credit_card/new(.:format)                   credit_card#new      edit_credit_card GET    /credit_card/:id/edit(.:format)              credit_card#edit           credit_card GET    /credit_card/:id(.:format)                   credit_card#show                       PATCH  /credit_card/:id(.:format)                   credit_card#update                       PUT    /credit_card/:id(.:format)                   credit_card#update                       DELETE /credit_card/:id(.:format)                   credit_card#destroy  

controller:

def new      @credit_card = CreditCard.new  end  

When I try to render by form it says:

undefined method `credit_cards_path' for #<#<Class:0x00000004c37680>:0x00000004c34570>  Did you mean?  credit_card_path                 credit_card_index_path                 credit_card_url  

Its a model based form, for now I have nothing in model. I just want to render and submit will go to create method

br html tag is not working in helper file

Posted: 27 Jul 2016 06:51 AM PDT

Here is the code I have in my helper file but it is not working:

link_to objs.try(:send,:name) , eval("edit_#{objs.try(:class).try(:name).try(:downcase)}_path(objs,action_name: action)") , remote: true,style: "color:  #{colour_picker_title objs.class.name.downcase} !important", data_toggle: "tooltip" ,class: "tooltip-class", title: ( get_right_by_role("delete_#{objs.class.name.downcase}_progress",objs.class.name.downcase) ? (objs.try(:send,:progresses).order("created_at DESC").limit(3).map{|pr| "#{pr.created_at.try(:strftime,"%d-%m-%Y")} : #{pr.description} <br>".html_safe}rescue "") : "")  

How to add line break after this:

map{|pr| "#{pr.created_at.try(:strftime,"%d-%m-%Y")} : #{pr.description} <br>".html_safe}  

Refile and 'aws-sdk' V2 gem getting Missing Region Error

Posted: 27 Jul 2016 06:51 AM PDT

I am using the latest version of the refile gem to upload images to AWS and it's working fine. when I try to test my app with rspec i get this error:

/aws-sdk-core/plugins/regional_endpoint.rb:34:in `after_initialize': missing region; use :region option or export region name to ENV['AWS_REGION'] (Aws::Errors::MissingRegionError)

Gemfile:

gem "refile", require: "refile/rails"

gem "refile-mini_magick"

gem "refile-s3"

refile.rb

require 'refile/simple_form'

require "refile/s3"

aws = {

access_key_id: ENV['AWS_ACCESS_KEY_ID'],

secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],

region: ENV['AWS_REGION'],

bucket: ENV['AWS_BUCKET']

}

Refile.cache = Refile::S3.new(prefix: "cache", **aws)

Refile.store = Refile::S3.new(prefix: "store", **aws)

I tried setting a new initializer aws.rb:

require 'aws-sdk'

Aws.config.update({ region: 'us-west-2', credentials: Aws::Credentials.new('akid', 'secret') })

but it did not work.

10x for your help!

Error initializing ShortCode Gem

Posted: 27 Jul 2016 06:30 AM PDT

I have a problem initializing the Rails Gem shortcode.

I have this code in initializers / shortcode.rb

Shortcode.setup do |config|      config.template_parser = :haml       config.template_path = "support/templates/chart"      config.block_tags = [:chart]    end  

When I start the server rails (rails s) gives the following error.

/home/usuario/proyectos/rails/crowdfunding/config/initializers/shortcode.rb:3:in `<top (required)>': uninitialized constant Shortcode (NameError)  from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/engine.rb:652:in `block in load_config_initializer'  from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/notifications.rb:166:in `instrument'  from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/engine.rb:651:in `load_config_initializer'  

Note: I already did install bundle and bundle update sass-rails

Rails: Transfer files via API

Posted: 27 Jul 2016 06:20 AM PDT

I want to transfer a large files (100 - 200 Mb) (or raw data) from iOS to Rails server (via some API). Files maybe aren't very large, but the transfer's speed can be low. What approach should I use? Should I use websockets? Or just split file on iOS into smaller chunks and transfer chunk after chunk? I would like to be able to monitor if whole file was successfully transfered. And resume transferring in case of Internet connection lost.

Compare Time In Rails

Posted: 27 Jul 2016 06:39 AM PDT

I need to be able to compare time in my rails app. Basically I have to compare my created_at timestamp and if the time in the timestamp is greater than say 10 AM then have to highlight the record as red in color in my view. How can i compare time to achieve this?

Rails html view, target one element and make it invisible for one view only.

Posted: 27 Jul 2016 07:16 AM PDT

I am looking to target a image which I currently have in my 'application.html.erb' layout view, so it only displays when the 'adventures/index.html.erb' view is displayed. I tried using the code #nav_img { display: none; } in the css file 'adventures.scss', however this does not work and if I wrote this in the 'application.scss' stylesheet, it would disable the image for every page - I only want it to be invisible on the 'adventure.index.html.erb' view. Many thanks.

Application.html.erb file:

<!DOCTYPE html>  <html>    <head>      <title>TFAA</title>      <%= csrf_meta_tags %>        <%= stylesheet_link_tag 'application','http://yui.yahooapis.com/2.8.1/build/reset/reset-min.css' %>      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>      <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>        <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>      <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,600' rel='stylesheet' type='text/css'>    </head>      <body>      <div class="container">    <!-- ================= nav bar ================= -->          <nav class="nav_bar">            <div class="nav_logo">            <%= link_to image_tag("nav_logo.png", id: "nav_img"), root_path %>          </div>            <ul class="nav_links">            <% if user_signed_in? %>              <li>                <%= button_to "Log out", destroy_user_session_path, id: 'button_log_out', class: 'button', method: :delete %>              </li>            <% else %>              <li>                <%= button_to "Log in", new_user_session_path, id: 'button_log_in', class: 'button', method: :get %>              </li>                <li>                <%= button_to "Sign up", new_user_registration_path, id: 'button_sign_up', class: 'button', method: :get %>              </li>            <% end %>          </ul>        </nav>    <!-- ================= flash notices ================= -->          <p class="notice"><%= notice %></p>           <p class="alert"><%= alert %></p>          <%= yield %>        </div>    </body>  </html>

adventures/index.html.erb file:

<!DOCTYPE html>  <html>    <head>      <meta charset="utf-8">      <title>Adventure</title>    </head>    <body>      <div class="adventure_logo">        <%= image_tag "nav_logo.png", id: 'main_logo' %>      </div>      <% @adventures.each do |adventure|%>        <%= link_to "#{adventure.title}", adventure_path(adventure.id), class: 'adventure' %>      <% end %>    </body>  </html>

 body {     font-family: 'Source Sans Pro', sans-serif;   }     .container {     margin: 2%;     background-color: lightgrey;   }     // ============= nav bar ==============     .nav_bar {     border: 1px solid blue;     height: 100px;     width: 100%;     display: flex;     justify-content: space-between;   }     .nav_logo {     border: 2px dashed orange;   }     #nav_img {     width: 300px;   }     .nav_links {     display: flex;     justify-content: center;     align-items: center;     border: 1px solid lightgreen;     width: 30%;   }     .button {     margin: 5px;     padding: 10px;     border-radius: 13px;     border: none;     color: white;     font-family: 'Indie Flower', cursive;     font-weight: 200;     text-decoration: none;   }     #button_log_in {     background-color: #8b0407;     width: 100px;   }     #button_sign_up {     background-color: #333333;     width: 100px;   }     // ============= forms ==============     .sign_up_form {     border: 1px solid green;   }     .sign_up_h2 {     border: 1px solid pink;   }     .sign_in_link {     border: 1px solid yellow;   }     .sign_up_link {     border: 1px solid purple;   }     .forgot_password {     border: 1px solid brown;   }     // ============= adventures ==============     .adventure {     border: 1px solid yellow;   }     .adventure_logo {     margin: 0 auto;     width: 70%;     display: flex;     justify-content: center;     align-items: center;     border: 1px dashed orange;   }     #main_logo {     max-width: 100%;     height: auto;     width: 70%;   }

adventures.scss file:

#nav_img {    display: none;  }

heroku pg:psql got error `require': cannot load such file -- dl/import

Posted: 27 Jul 2016 05:55 AM PDT

when I tried to do heroku pg:psql --remote origin

C:\Sites\allmain\actest>heroku pg:psql --remote origin  Your version of git is 1.9.4.. Which has serious security vulnerabilities.  More information here: https://blog.heroku.com/archives/2014/12/23/update_your_git_clients_on_windows_and_os_x  ---> Connecting to DATABASE_URL  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121:in `require': cannot load such file -- dl/import (LoadError)          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/pageant.rb:1:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent/socket.rb:5:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent.rb:22:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/key_manager.rb:4:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/session.rb:4:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh.rb:11:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/net-ssh-gateway-1.2.0/lib/net/ssh/gateway.rb:2:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/heroku-3.43.5/lib/heroku/helpers/heroku_postgresql.rb:54:in `maybe_tunnel'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/heroku-3.43.5/lib/heroku/command/pg.rb:149:in `psql'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/heroku-3.43.5/lib/heroku/command.rb:212:in `run'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/heroku-3.43.5/lib/heroku/cli.rb:34:in `start'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/heroku-3.43.5/bin/heroku:24:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/bin/heroku:23:in `load'          from C:/RailsInstaller/Ruby2.2.0/bin/heroku:23:in `<main>'  

I am using

Windows 7    heroku-gem/3.43.5 (i386-mingw32) ruby/2.2.4  heroku-cli/5.2.30-bb2a990 (windows-386) go1.6.2  

Named routes for nested resources

Posted: 27 Jul 2016 06:01 AM PDT

I'm actually having trouble finding the documentation for this so if you have a link handy that would be really appreciated too.

So I have:

resources :users do     resources :posts, only: [:index, :create, :show]     end  

I wanted to access the index action of posts through a named route. I tried this: <%= link_to 'User Posts', user_posts_path %> but it said it was missing user_id. Any ideas?

Need double colon as prefix for constant lookup?

Posted: 27 Jul 2016 05:50 AM PDT

I use builder templates within a legacy Rails application. But I got the following error after upgrading to Rails 4.2 and making some adaptions.

Formatter cannot be autoloaded from an anonymous class or module  

The class Formatter is required before rendering the XML. The template has some strange extensions of the xml object.

Formatter # no error    class << xml    def some      data(Formatter.format(@input)) # raises the error above    end  end    xml.instruct!()  xml.test { xml.some }  

I have no idea how the constant got lost. I have the same problem with classes form the standard library like BigDecimal. It seems that all made require calls are reseted in the context.

Prefixing all classes with :: is the workaround. Then the Rails constant lookup is triggered and reloads the classes.

Any ideas how to get the constants back?

Chart.js data/label scale

Posted: 27 Jul 2016 07:00 AM PDT

I want to create a linechart for a intern project at my company. On the yAxis I want orders. On the xAxis I want month( Jan - Dec). So there are 12 labels on the xAxis. My problem is that only the first 12 orders get picked from data:. How can I fix this ? The same problem is with a month. I put a link to illustrate in here. http://imgur.com/a/VJBvj And here is my code:

 <canvas id="orderChartCurrentMonth" width="400" height="400"></canvas>  <script>    <%= foo = ((Date.today).beginning_of_month) %>    var ctx = document.getElementById("orderChartCurrentMonth");    var orderChartCurrentMonth = new Chart(ctx, {      type: 'line',      data: {        labels: [          "<%=foo %>", "<%=foo + 1.week%>", "<%=foo + 2.week %>","<%=foo + 3.week%>", "<%=foo + 4.week%>"        ], //x-Achse        datasets: [{          label: 'Graph Orders last week',          data: <%= (foo..foo.end_of_month).map { |date| Company.graph_order(date).to_f}.inspect  %> //y-Achse        }]},      options:{        legend:{          display: false        },        scales: {          xAxes: [{            ticks: {              stepSize: 10        }}]}}})  </script>  

Greetings

NoMethodError: undefined method `within' for main:Object

Posted: 27 Jul 2016 06:13 AM PDT

I'm trying to make Capistrano deploy script.

In my Capfile I make sure all rake tasks are included

# Load tasks  Dir.glob('config/capistrano_tasks/*.rake').each { |r| import r }  

Next I have a 'migrations.rake' containing:

namespace :fileservice do      task :migrate do          within release_path do              info 'Doing migrations'                execute :php, fetch(:symfony_console_path), 'doctrine:migrations:migrate', '--no-interaction', fetch(:symfony_console_flags)          end      end  end  

In my deploy.rb I call the task at the very end with:

after 'deploy:publishing', 'fileservice:migrate'  

For some reason I keep getting an error saying:

NoMethodError: undefined method `within' for main:Object  

I have no idea where to look or what might be wrong... When googling I get a lot of "NoMethodError" hits but none about the 'within' method and most are general Ruby errors.

Where should "within" be defined? I dat a ruby on rails thing? Or capistrano?

Hopefully someone knows where to start looking or which library / script to include!

UPDATE: I just discovered that none of the methods work. When removing lines I got the same error for "info" and "execute".... So I guess somewhere, something is missing.....

How to filter results by their associations when using PG search gem?

Posted: 27 Jul 2016 06:31 AM PDT

I am using PG search gem in my Rails app. Say I get a set of articles in my controller:

@articles = Article.search(params[:search]).with_pg_search_highlight  

the problem with PG search here is that I get back an array, instead of AR object. So now I cannot do something like

@research_articles = @articles.where(category: 'research')  

Because I will get a

undefined method `where' for Array  

Now I can make several queries from that one action, but what would be a better solution to this problem?

select dropdown and each block - Ruby/Rails

Posted: 27 Jul 2016 07:44 AM PDT

I have a simple each block that takes each category and creates an option

@categories = Category.all    <select id="bike_category_filter" multiple="multiple">    <% @categories.each do |c| %>      <option value="<%= c.name %>"><%= c.name %></option>    <% end %>  

What I would like to with the categories Men and Women (so c.name) is surround them with an <optgroup> tag. How could I achieve that, a link to a resource or explanation on where to look would suffice, not necessarily looking for someone to give me the answer

The desired output would look like

<select>    <optgroup label="Gender">      <option value="cat1">Men</option>      <option value="cat2">Women</option>    </optgroup>      <option value="cat3">Cat5</option>      <option value="cat4">Cat4</option>  </select>  

Thanks

How to have three models linked in rails

Posted: 27 Jul 2016 05:44 AM PDT

I currently have a User model, Chasing model and a Comments model.

The User has_many :chasings and the Chasing model belongs_to :user and has_many :comments

I created a migration to add a reference to :chasings for :user, so I could call Chasing.user:

class AddUsersToChasings < ActiveRecord::Migration    def change      add_reference :chasings, :user, index: true, foreign_key: true    end  end  

So I can now successfully assign chasings to users, however I'm wanting to find out the best way of assigning comments in chasings to users using a similar select list as below (this is the code for selecting users for chasings):

    <%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}, @chasing.user_id), { :include_blank => "Please select user"}, {:class => "form-control"} %>  

Anyone got any ideas on how I'd create the relationship between comments and users, if the comments already belong_to the chasing?

Some simple math isn't working in my helper

Posted: 27 Jul 2016 05:09 AM PDT

I've got a grade function:

def grade(submission)  score_counter = 0  total_score = submission.test.questions.size    #the scoring logic is here    return (score_counter/total_score)*100  end  

The intention is to return a percent score, but all that shows up in my view is 0. If I just try to return score_counter and total_score separately, they display the correct values. Any ideas?

Where store configuration mangopay?

Posted: 27 Jul 2016 05:19 AM PDT

I want add mangopay payment system for received money from users.

Where need I add configuration in project?

configuration

MangoPay.configure do |c|    c.preproduction = true    c.client_id = 'YOUR_CLIENT_ID'    c.client_passphrase = 'YOUR_CLIENT_PASSWORD'  end  

And maybe can who show examples project ruby on rails with using mangopay?

Thank for advance

Updating user information outside devise pages

Posted: 27 Jul 2016 05:03 AM PDT

I want to add the option for the user to edit his email/password/image... from the /settings page not from the /users/edit page. So I copied the code to the settings page

    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>    <%= devise_error_messages! %>    <div class="field">      <%= f.label :email %><br />      <%= f.email_field :email, autofocus: true %>    </div>      <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>      <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>    <% end %>      <div class="form-group">      <%= f.label :image %>      <%= f.file_field :image, class: 'form-control'%>    </div>      <div class="form-group">      <%= f.label :cover %>      <%= f.file_field :cover, class: 'form-control'%>    </div>      <div class="field">      <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />      <%= f.password_field :password, autocomplete: "off" %>    </div>      <div class="field">      <%= f.label :password_confirmation %><br />      <%= f.password_field :password_confirmation, autocomplete: "off" %>    </div>      <div class="field">      <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />      <%= f.password_field :current_password, autocomplete: "off" %>    </div>      <div class="actions">      <%= f.submit "Update" %>    </div>  <% end %>    <h3>Cancel my account</h3>    <p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>    <%= link_to "Back", :back %>  

but it returned this

undefined local variable or method `resource' for #<#<Class:0x007f60245ab9b0>:0x007f6026f58358>  

What should I add to my controller?

Error :While rendering the RSolr::HashWithResponse from rails controller + ember

Posted: 27 Jul 2016 04:43 AM PDT

hi all i am bit new with ember, i am getting this error

Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using ui@serializer:application:) at new Error (native)

while rendering my rsolar responce.

Can any one guide us in which format we should render.

ember model:    export default Model.extend({        title_s: attr()   });      ember controller:      var resu = this.get('store').findAll('search')  

data which i have to render in rails controller is like this :

 {"responseHeader"=>{"status"=>0, "QTime"=>0, "params"=>{"q"=>"*:*", "wt"=>"ruby"}},   "response"=>    {"numFound"=>6,     "start"=>0,     "docs"=>      [        {"id"=>"1",        "title_s"=>"java se",        "title_txt"=>["java se"],        "company_name_s"=>"cts",        "company_name_txt"=>["cts"],        "job_description_s"=>"it",        "job_description_txt"=>["it"],        "category_name_s"=>"it",        "industry_s"=>"it",        "created_at_s"=>"10-05-16",        "job_type_s"=>"permenant",        "city_s"=>"delhi",        "state_s"=>"delhi",        "salary_type_s"=>"monthly",        "salary_s"=>"100000",        "status_b"=>true,        "_version_"=>1540288621613940736       }      ]    }  }  

please help me out.

thanks in advance

Action mailer not sending/receiving email rails 5

Posted: 27 Jul 2016 06:49 AM PDT

I'm trying to create a simple blog (using rails 5) and want to send email updates when to users when I post something new. I'm trying to use actionmailer and I'm using devise to register users. I'm trying to set it up with just the first user initially.

When I look at my local server the email appears to be sending but it's not received. Any advice would be very welcome I've been stuck a while.

    UserNotifierMailer#sample_email: processed outbound mail in 410.4ms  Sent mail to myemail@gmail.com (853.2ms)  Date: Wed, 27 Jul 2016 12:05:33 +0100  From: from@example.com  To:myemail@gmail.com  Message-ID: <5798957d9de31_ae813ff962abfe1466438@Unknown-7c-d1-c3-78-04-d2.home.mail>  Subject: Sample Email  Mime-Version: 1.0  Content-Type: multipart/alternative;   boundary="--==_mimepart_5798957d951e2_ae813ff962abfe1466312";   charset=UTF-8  Content-Transfer-Encoding: 7bit  

My posts controller looks like this:

def create      @user = User.first      @post = current_user.posts.build(post_params)      if @post.save        flash[:success] = "Your post has been created!"        UserNotifierMailer.sample_email(@user).deliver        redirect_to posts_path      else        flash[:alert] = "Your new post couldn't be created!  Please check the form."        render :new      end    end  

My mailer looks like this:

class UserNotifierMailer < ApplicationMailer    default from: "from@example.com"    def sample_email(user)      @user = user      @url = 'http://www.google.com'      mail(to: @user.email, subject: 'Sample Email')    end  end  

and in my development.rb I have these settings:

config.action_mailer.raise_delivery_errors = true    config.action_mailer.perform_deliveries = true    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }      config.action_mailer.delivery_method = :smtp      config.action_mailer.smtp_settings = {      address: "smtp.gmail.com",      port: 587,      domain: "gmail.com",      authentication: "plain",      enable_starttls_auto: true,      user_name: "my_gmail_username",      password: "my_gmail_password"    }  

Attach an instance of model within Migration

Posted: 27 Jul 2016 06:44 AM PDT

I'm creating a User model which is associated with a Cart model. At the moment the User is created, a Cart should automatically be created.

In the app, I added the call Cart.create into the create method of my UserController.

When I try to seed the data, however, I need to have two lines: User.create and Cart.create and attempt to make this work for only one line of User.create.

Is it possible to move the Cart creation code into method change (CreateUsers, Migration)?

An error occurred while installing mysql2 (0.3.14)

Posted: 27 Jul 2016 04:54 AM PDT

screen shot of myerror I Installed Mysql-server, libmysqlclient-dev, ruby-mysql, mysql-client, libmysqld-dev

But still this issue occurs.Could not continue my project.

Environment: rails version - 4.2.6 , ruby - 2.3, mysql - 5.7

How to do Email Validation in Ruby on Rails?

Posted: 27 Jul 2016 04:52 AM PDT

I am doing email validation in rails and do

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i  

Also do HTML5 validation on frontend but email likes

..abc@gmail.com  .abc@gmail.com  

are still validated

Skip recaptcha across the application

Posted: 27 Jul 2016 04:12 AM PDT

I am using https://github.com/ambethia/recaptcha/. I want to bypass recaptcha for certain users across all the pages. Right now I have done changes in the pages where recaptcha is required. Need to know if there is a global solution which will apply across all the pages?

Ruby on rails legacy application error with linecache gem [duplicate]

Posted: 27 Jul 2016 04:18 AM PDT

This question already has an answer here:

I have ruby on rails legacy application and I have the following error when I run the application

/usr/local/lib/ruby/gems/1.9.1/gems/linecache19-0.5.12/lib/trace_nums19.so: undefined symbol: ruby_current_thread - /usr/local/lib/ruby/gems/1.9.1/gems/linecache19-0.5.12/lib/trace_nums19.so (LoadError)    /usr/local/lib/ruby/gems/1.9.1/gems/linecache19-0.5.12/lib/tracelines19.rb:12:in `require'    /usr/local/lib/ruby/gems/1.9.1/gems/linecache19-0.5.12/lib/tracelines19.rb:12:in `rescue in <module:TraceLineNumbers>'  

Full error can be found Here

Could anyone help me spot the problem?

Compress and upload multiple images [duplicate]

Posted: 27 Jul 2016 03:43 AM PDT

This question already has an answer here:

I am working on a form with 8 images to be uploaded using the camera capture(in phone) / file upload(in desktop) where each image will be of minimum size 2 MB..

It takes too long to upload the file to the server. I need to upload the images through form submit and not by AJAX..

Is there any way to compress large image and then upload it to server. How can I submit the form where it should take minimum time to submit..

I came across CANVAS with HTML5 but, I don't know whether it will be used for this situation, if it can be used then please give me some example code..

Thank you..

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. Ruby on Rails Online Course Hyderabad

    ReplyDelete