Friday, November 4, 2016

Rails: Ransack not sorting date | Fixed issues

Rails: Ransack not sorting date | Fixed issues


Rails: Ransack not sorting date

Posted: 04 Nov 2016 08:15 AM PDT

I've decided to add Ransack to my application for searching, but, to be honest, it seems to be really glitchy. On the other hand, this is my first time incorporating a gem, so maybe I'm doing something wrong.

My search form allows users to dynamically add and remove search conditions, like this. Here's a few issues. First, my controller code:

  def search      @search = Student.search(params[:q])      @search.sorts = 'date_entered' if @search.sorts.empty?      @students = @search.result.includes(:exams).to_a.uniq      @search.build_condition    end  

1.) The "build_condition" nicely creates one empty, default search box when you go the search page. However, after submitting a search, it meanly adds a second empty search box beneath the one you just searched on. Kind of ugly. Anyone know how to prevent that?

2.) The 'date_entered' sort doesn't actually sort anything. date_entered is of type Date. The search does work if I change it to 'student_name' ... but I want to search by date_entered, not student_name.

Rails: Triple nested forms example

Posted: 04 Nov 2016 08:11 AM PDT

I have looked around for weeks trying to find an example of triple nested forms that include all the components, including how to handle form_for with the deeply nested model. Fairly new to Rails, but would love if someone could show post an example of a triple nested form_for for something like Group->Project->Tasks, showing controller, model and view connection. Having a difficult time with the Tasks form_for. Thanks.

Passing params in Rails controller for multiple inputs automatically

Posted: 04 Nov 2016 07:58 AM PDT

In my user edit form I have the following HTML:

<p>Name: <%= f.text_field :name %></p>    <p>Email: <%= f.text_field :email %></p>    <% for role in Role.all %>      <p>        <%= check_box_tag "user[roles][]", role.id, @user.roles.include?(role) %>        <%= role.name %>      </p>  <% end %>  

So I have name, email and a bunch of associated roles.

Normally in the controller I would do something like:

@user = User.new(user_params)  

and the params being:

def user_params    params.require(:user).permit(:name, :email)  end  

However how do I handle the saving of the roles? And can I just auto-save all the params on the form without having to declare them manually.

I tried this:

if @user.update(params)  

But it didn't work. Is there a way to just save all the params to the correct models?

Delayed Job - Force retry later

Posted: 04 Nov 2016 08:11 AM PDT

Is there an idiomatic way, or any way at all, to force a delayed job to retry on its own? I have an automated email model that sometimes fails if a user hasn't assigned a particular attribute to it. However, some users do this within a few hours. We wanted to facilitate a way for the users who fix their data in an appropriate time to have their email retried. However, the way I'm currently implementing it is not working.

class AutomatedEmail < ActiveRecord::Base    def enqueue_job      Delayed::Job.enqueue Prepare.new(id), priority: 20, run_at: Time.zone.now    end      def send!      # send    end      class Prepare      class UnassignedError < StandardError; end        def initialize(automated_email_id)        @automated_email_id = automated_email_id      end        def perform        raise UnassignedError if # AutomatedEmail is in a bad state          automated_email.send!      end        def error(job, exception)        if exception.class == UnassignedError          job.run_at = job.run_at + # incremented value          job.save!        end      end        def failure(_)        # notify that we've deferred until we could no more      end        private def automated_email        AutomatedEmail.find_by_id(@automated_email_id)      end    end  end  

The goal is to retry 5 times within 6 hours (15min, 1hr, 3hr, 6hr). If the specific issue is the cause of the failure, do something with it, otherwise have Delayed::Job handle it as it normally would.

Essentially, I want to do is more or less something like so:

class AutomatedEmail < ActiveRecord::Base    def enqueue_job      Delayed::Job.enqueue Prepare.new(id), priority: 20, run_at: Time.zone.now    end      def send!      # send    end      class Prepare      def initialize(automated_email_id)        @automated_email_id = automated_email_id      end        def perform        update job.run_at && retry if # AutomatedEmail is in bad state          automated_email.send!      end        def failure(_)        # detect that the failure was due to the specific invalid state from before        # and do something about it      end        private def automated_email        AutomatedEmail.find_by_id(@automated_email_id)      end    end  end  

How to use same variable across various controllers - ruby on rails

Posted: 04 Nov 2016 07:41 AM PDT

I am using ruby 2.3.1 and rails 3.2.1. I need to initialize a variable called has_sub_menu = false in application controller.

In my application i am using more than 30 controllers and only two controllers contains sub-menu, so i need to assign has_sub_menu = true to these controllers to validate it in layout file.

This is my application.rb

has_sub_menu = false  

some_controller01.rb

has_sub_menu = true  

some_controller02.rb

has_sub_menu = true  

I tried like this in layout.rb,

if controller.has_sub_menu == true    show_menu_items  end  

show_menu_items will be available in that two controller and currently i am not able to access the has_sub_menu value in layout file

I know in c# I can declare the variable as static and access it in any file using object.

Like wise how can i declare a variable in application controller and assign different value to that variable in other two controller and I need to access that value in layout.rb file for sub-menu validation.

An error occurred while installing byebug (2.7.0), and Bundler cannot continue

Posted: 04 Nov 2016 08:07 AM PDT

I am getting following error when i am doing bundle install or bundle udpate

An error occurred while installing byebug (2.7.0), and Bundler cannot  continue.  Make sure that `gem install byebug -v '2.7.0'` succeeds before bundling.  

I am also getting error

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.  

If i do sudo gem install byebug -v '2.7.0' i get

Building native extensions.  This could take a while...  Successfully installed byebug-2.7.0  Parsing documentation for byebug-2.7.0  unable to convert "\xCA" from ASCII-8BIT to UTF-8 for lib/byebug/byebug.bundle, skipping  1 gem installed  

and then if i do bundle install or bundle udpate i get same error.

I tried removing byebug from gem file but then if i try to go to console, i get

bin/console:6:in `require': cannot load such file -- byebug (LoadError)      from bin/console:6:in `<main>'  

here's the gemfile

gem 'roll_out'  gem 'roll_out-jira'  gem 'philter', '~> 1.11.0'    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'pry-byebug'  # An IRB alternative and runtime developer console  gem 'pry', '~> 0.9.12'  # Walk the stack in a Pry session  gem 'pry-stack_explorer', '~> 0.4.9'  # Simple, feature rich ascii table generation library  gem 'terminal-table', '~> 1.5', '>= 1.5.2'  # Great Ruby dubugging companion: pretty print Ruby objects to visualize their structure.  # Supports custom object formatting via plugins  gem 'awesome_print', '~> 1.6', '>= 1.6.1'    # BDD for Ruby  gem 'rspec', '~> 3.1.0'  # Code coverage for Ruby 1.9+ with a powerful configuration library and automatic merging of coverage across test suites  gem 'simplecov', '~> 0.7.1'  # factory_girl provides a framework and DSL for defining and using factories - less error-prone,  # more explicit, and all-around easier to work with than fixtures.  gem 'factory_girl', '~> 4.0'  # Faker, a port of Data::Faker from Perl, is used to easily generate fake data: names, addresses, phone numbers, etc.  gem 'faker', '~> 1.6', '>= 1.6.6'  #gem 'wellness_client'  

Executing ruby/perl/python scripts without mentioning complete path in Rails

Posted: 04 Nov 2016 07:26 AM PDT

I have nearly 100 ruby/perl/python scripts. I want to execute a script which is chosen from the drop down list in the view of Rails.(I know how to execute non ruby scripts from ruby.)

Where is the best place to keep those scripts so that I don't have to mention the complete path to those scripts while executing?

no method error on ruby on rails

Posted: 04 Nov 2016 07:23 AM PDT

I'm beginner of rails. what I'm trying to do is making a form which has only title and content and building a database that can save them.

This is my migrate file

class CreateMelons < ActiveRecord::Migration    def change      create_table :melons do |t|          t.string :title        t.text :content          t.timestamps null: false      end    end  end  

And this is my controller

 def write          @title =params[:title]          @content = params[:content]            @new_post = Melon.new          @new_post.title =params[:title]          @new_post.content =params[:content]          @new_post.save            redirect_to "/list"          end  

And the error messages are here.

undefined method `title=' for #<Melon id: nil, created_at: nil, updated_at: nil>  

I don't know what the reason is. There's title column! And I've executed rake db:migrate command. Please help me!

How to split geojson data sent from Rails using AJAX

Posted: 04 Nov 2016 07:21 AM PDT

I've been following this post on how to send geojson from rails using AJAX. I can easily send either dataset and manipulate it in my coffeescript, but I'm stumped on how to break it apart if I send both. Rails controller code

@paths = Path.select("id, geom, path_name").where("ispub is true").order("id")  feature_collection = Path.to_feature_collection @paths  @geopaths = RGeo::GeoJSON.encode(feature_collection)    @beds = Bed.select("id, geom, bed_name").where("ispub is true").order("id")  feature_collection = Bed.to_feature_collection @beds  @geobeds = RGeo::GeoJSON.encode(feature_collection)    data = { paths: @geopaths, beds: @geobeds }      respond_to do |format|    format.json { render json: data }    format.html  end  

AJAX request in coffeescript

  $.ajax      dataType: 'text'      url: 'map.json'      data: {        'paths' : paths        'beds' : beds       }      success: (data) ->        pathMarkers = L.geoJSON(JSON.parse(data.paths), style: pathStyle)        bedMarkers = L.geonJSON(JSON.parse(data.beds), style: bedStyle)  

Rails ActiveRecord relationships for has_and_belongs_to_many

Posted: 04 Nov 2016 07:25 AM PDT

What would the correct relationships in Rails be for this setup:

users    id    name    email    roles    id    name    permissions    id    name    users_roles    id    user_id    role_id    roles_permissions    id    role_id    permission_id  

I then have the following models:

class User < ActiveRecord::Base  end    class Role < ActiveRecord::Base    has_and_belongs_to_many :users, :join_table => 'users_roles'  end    class Permission < ActiveRecord::Base    has_and_belongs_to_many :roles, :join_table => 'roles_permissions'  end  

Is this correct? As when I try and access:

@user = User.find(params[:id])  @user.roles  

I get the error: undefined method 'roles' for #<User:0x007fc0176c6b08>

So it seems the relationships are not setup properly.

Rails installation issue on Windows 10. Everything but Rails

Posted: 04 Nov 2016 08:20 AM PDT

I've tried to install Ruby on Rails, 3 or 4 different times from different sources. I seem to have everything I need except Rails. When I type "rails --version" it says:

"The system cannot find the path specified".

It says I have Ruby 2.2.4 and Node is 6.9.1, but no Rails. I'm using Windows 10. I'd really appreciate any help, thanks!!!

Sending mail through Google smtp in Rails 5

Posted: 04 Nov 2016 06:57 AM PDT

I've done a LOT of digging, and I still haven't been able to find an answer. After signing up with devise, an e-mail gets sent to activate the account. The mail works with my e-mail, and I even got a friend of mine to sign up (after messing with the settings for a while), but after that another person tried to sign up but the e-mail wasn't sent to them, and Google sent me another message saying "someone has your password" again.

Here's production.rb

config.action_mailer.perform_deliveries = true  config.action_mailer.raise_delivery_errors = true  host = 'website.com'  config.action_mailer.default_url_options = { host: host }  config.action_mailer.delivery_method = :smtp  config.action_mailer.smtp_settings = {    :address => "smtp.gmail.com",    :port => 587,    :user_name => ENV["email_hidden"],    :password => ENV["password_hidden"],    :authentication => :plain,    :enable_starttls_auto => true  }  

I turned access for less secure apps on, and I did the unlock captcha thing for gmail. I also turned on IMAP in my gmail settings. Again, I got one friend to sign up, but a day later someone else tried and the e-mail wasn't sent, and an error showed up on the web page.

Someone pleeease heeeeelp

How to query params in nested attributes writer

Posted: 04 Nov 2016 06:59 AM PDT

In my nested attributes writer some of my attributes have id's and some don't:

attributes => [{"id"=>23, "name"=>"John Doe"}, {"name"=>"Jane Doe"}]  

I want destroy an object unless its id is included in the attributes array. I don't know how to properly query the attributes, so am doing it like this for now:

id_array = attributes.collect{|a| a[:id]}  object.destroy unless id_array.include(object.id)  

I'd prefer to avoid creating the id_array and instead accomplish it in one line to match this pseudocode:

object.destroy UNLESS THERE'S AN ATTRIBUTE ELEMENT WITH SAME ID  

Having trouble coming up with a query that works on attributes though.

Rails auto-reload! third party service

Posted: 04 Nov 2016 06:49 AM PDT

My app is connected to some third-party APIs.

I have several APIconnector module-singletons that are initialized only once at application start (initialized means the client is instanciated once with the credentials retrieved from secrets)

When I reload! the application in my console, I am losing those services and I have to exit and restart the console from scratch.

Basically all my connectors include a ServiceConnector module like this one

module ServiceConnector    extend ActiveSupport::Concern      class ConnectorError < Exception    end      class ActivationError < ConnectorError    end      included do      @activated = false      @activation_attempt = false      @client = nil        attr_reader :client, :activated        def self.client        @client ||= service_client      end        def self.service_name        name.gsub('Connector', '')      end        def self.activate        @activation_attempt = true        if credentials_present?          @client = service_client          @activated = true        end      end  

Here is an example of a service implementation

module My Connector    include ServiceConnector      @app_id = nil    @api_key = nil      def self.set_credentials(id, key)      @app_id = id      @api_key = key    end      def self.credentials_present?      @app_id.present? and @api_key.present?    end      def self.service_client      ::SomeAPI::Client.new(        app_id: @app_id,        api_key: @api_key      )    end  end  

I use this pattern that lets me reuse those services outside Rails (eg Capistrano, worker without Rails, etc.). In Rails I would load the services that way

# config/initializers/my_service.rb  if my_service_should_be_activated?    my_service.set_credentials(      Rails.application.secrets.my_service_app_id,      Rails.application.secrets.my_service_app_key    )    my_service.activate  end  

I guess that executing reload! seems to clear all my instance variables inclusing @service.

Is it possible to add code to be executed after a reload! ? In my case I would need to re-run the initializer. Or is there a way to make sure the instance variables of my services are not cleared with a reload! ?

Where should I run scheduled background jobs?

Posted: 04 Nov 2016 07:53 AM PDT

Here in my company we have our regular application in aws ebs with some background jobs. The problem is, these jobs are starting to get heavier and we were thinking in separate them from the application. The question is: Where should we do it?

We were thinking in doing it in aws lambda, but then we would have to port our rails code to python, node or java, which seems to be a lot of work. What are other options for this? Should we just create another ec2 environment for the jobs? Thanks in advance.

Pass non model parameter to controller action

Posted: 04 Nov 2016 06:49 AM PDT

How do I pass those arguments which are not of model to a controller?

script.rb

class Script < ActiveRecord::Base     attr_accessor :directory     attr_accessor :xmlFile  end  

show.html.erb

<h1><%= @script.Name %></h1>    <%= simple_form_for @script, :url => script_execute_path(script_id: @script.id) do |f| %>    <%= f.input :directory %>    <%= f.input :xmlFile %>    <%= f.button :submit, 'Run' %>  <% end %>  

Here directory and xmlFile are used for taking inputs but it is not a part of Script model. Now I need to pass values contained in directory and xmlFile to my execute controller action

  def execute       @script = Script.find(params[:script_id])      #something like this -- @xmlFile = params[:xmlFile]    end  

how do I access it here?

ActionView::Template::Error (couldn't find file 'magnific-popup') on Heroku

Posted: 04 Nov 2016 06:40 AM PDT

I am working on Rails 3.2.17 where facing issue on Heroku when pushed code. It is working fine in local.

Actually, application already working fine on Heroku but after some changes pushed then show me error which I tried lots but not find proper solutions.

ActionView::Template::Error (couldn't find file 'magnific-popup'  2016-11-04T13:31:33.339935+00:00 app[web.2]:   (in /app/app/assets/stylesheets/application.scss:2)):  2016-11-04T13:31:33.339936+00:00 app[web.2]:     69:     = favicon_link_tag "travelshopa_Pin_SM_Icon-01_big.png"  2016-11-04T13:31:33.339937+00:00 app[web.2]:     70:     meta name="viewport" content="width=device-width, initial-scale=1.0"  2016-11-04T13:31:33.339938+00:00 app[web.2]:     71:     meta name="p:domain_verify" content="8190160645e8dabcaa234d75587f59aa"  2016-11-04T13:31:33.339939+00:00 app[web.2]:     72:     = content_for?(:stylesheet) ? yield(:stylesheet) : stylesheet_link_tag('application')  2016-11-04T13:31:33.339939+00:00 app[web.2]:     73:     / = stylesheet_link_tag "print", media: "print"  2016-11-04T13:31:33.339940+00:00 app[web.2]:     74:     = csrf_meta_tag  2016-11-04T13:31:33.339941+00:00 app[web.2]:     75:     script src="//cdn.mouseflow.com/projects/905e8269-8408-434b-9f68-cb0a2847579c.js" async=""  2016-11-04T13:31:33.339942+00:00 app[web.2]:   app/views/layouts/application.html.slim:72:in `_app_views_layouts_application_html_slim__1613734431592662227_70052446378020'  2016-11-04T13:31:33.339942+00:00 app[web.2]:   app/controllers/main_controller.rb:36:in `new_home'  

I precomplied already on Heroku manytimes but still not solved it.

Anyone have a idea then share it.

Thanks

Rails: Ransack doesn't search associated models properly

Posted: 04 Nov 2016 06:24 AM PDT

I followed the very useful Ransack Railscast but it doesn't work correctly on nested attributes.

I have a student model with a nested model, exams. Exams contain a subject, grade, and type. I can search for a student by the attributes of the student class, or by the attributes of the exams class.

So, if I search for all exams of History, it will return all students who have a History exam in their record. Which is good.

But suppose I search by students who took both a History exam and an English exam. It always returns zero students, even though many students took both.

It will only return true if I search across a single exam -- that is, a history exam with a score of 80. I can't search for two different exams at the same time, even though there are many students who have both exams on in their record.

I followed the code exactly from the Railscast. Why doesn't this work the way it should?

Rails folder structure

Posted: 04 Nov 2016 06:24 AM PDT

I have a script which is using rspec tests for automation of the rails app. I don't want to put the file "automation.rb" in the spec folder or in the lib folder (don't want a gem for this code).

My question is: Can we have custom folders in addition to the standard ones in the rails directory structure. Eg. a folder like automation in the root directory of rails app.

How to merge multiple and different ActiveRecord query in rails and paginate over the records?

Posted: 04 Nov 2016 06:35 AM PDT

I have two similar tables in rails named as messages and message_histories. Periodically we remove the old data from messages table and drop it in message_histories .

Now , I want to generate a report on the count of messages grouped by app_id which is present in message and message_history table .

Is there a way to Query [Message & MessageHistory ] Model and paginate on the records .

Currently I use the following Step , It looks weird but suggest a better way to do this :

@messages = Message.select("SUM(devices_count) as count ,CAST(run_at AS DATE) AS date").where(:app_id => @app.id).where("last_run_date is not ?", nil).group("CAST(run_at AS DATE)").order("date desc")  @messages << MessageHistory.select("SUM(devices_count) as count ,CAST(run_at AS DATE) AS date").where(:app_id => @app.id).where("last_run_date is not ?", nil).group("CAST(run_at AS DATE)").order("date desc")  @messages = @messages.flatten.paginate(:page => params[:page] || 1, :per_page => 100)  

getting Net::OpenTimeout: execution expired only sometimes

Posted: 04 Nov 2016 05:58 AM PDT

My rails application sends emails through a gmail account using mailer. Till recently everything was working fine. But now sometimes I get the error as

"Net::OpenTimeout: execution expired"   

This happens sometimes and sometimes it works. I want to know the reason for this behavior. Is it because of the gmail server having load balancing issues or is it because of some configuration issues in the rails app?

How to add composite primary keys in db using Rails?

Posted: 04 Nov 2016 05:57 AM PDT

I'm using Rails 5.0 with Postgresql 9.5

I'm in need to add composite primary keys to my model 'User_achievement' (to link 'User' and 'Achievement' models as you may guess).

So I tried using the "composite_primary_keys" gem. I followed all the instructions, nevertheless, the result wasn't like I expected. Seems like it doesn't create pkey in the 'user_achievement' table according to the info by psql tool:

test1_development=> \d user_achievements    Table "public.user_achievements"  Column | Type | Modifiers     ----------------+---------+-----------    user_id | integer |   achievement_id | integer |   uach_date | date |     Indexes:    "index_user_achievements_on_achievement_id" btree (achievement_id)    "index_user_achievements_on_user_id" btree (user_id)    Foreign-key constraints:    "fk_rails_4efde02858" FOREIGN KEY (user_id) REFERENCES users(id)    "fk_rails_c44f5b3b25" FOREIGN KEY (achievement_id) REFERENCES achievements(id)  

Here's models and migrations' code:

class CreateUsers < ActiveRecord::Migration[5.0]   def change    create_table :users do |t|    t.string :name    end   end  end    class CreateAchievements < ActiveRecord::Migration[5.0]   def change    create_table :achievements do |t|    t.string :ach_name    t.text :ach_desc    end   end  end    class CreateUserAchievements < ActiveRecord::Migration[5.0]    def change     create_table :user_achievements, id: false do |t|     t.belongs_to :user, :foreign_key => [:id]     t.belongs_to :achievement, :foreign_key => [:id]     t.date :uach_date     end    end   end      class Achievement < ApplicationRecord    has_many :user_achievements  end    class User < ApplicationRecord    has_many :user_achievements  end    class UserAchievement < ApplicationRecord    self.primary_keys = :user_id, :achievement_id    belongs_to :user, :foreign_key => [:id]    belongs_to :achievement, :foreign_key => [:id]  end  

So should the gem alter db tables? or it influences just the rails' environment? Is there the only way to alter db - to add execute line in migration?

Rails where query fails when using variable in query

Posted: 04 Nov 2016 07:22 AM PDT

Can some Rails expert throw some light on this behaviour in Rails 4:

>query_string = "agent_id = '1'"   => "agent_id = '1'"    >Lead.includes('agents').where(query_string).length   ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'agent_id' in 'where clause'    >Lead.includes('agents').where(agent_id = '1').length   Lead Load (0.5ms)  SELECT `leads`.* FROM `leads` WHERE (1)   LeadsAssignment Load (0.4ms)  SELECT `leads_assignments`.* FROM `leads_assignments` WHERE `leads_assignments`.`lead_id` IN (1, 2, 3, 4, 5)  Agent Load (0.5ms)  SELECT `agents`.* FROM `agents` WHERE `agents`.`id` IN (1, 2)   => 5  

The two queries should be identical. Why would one fail and the other not?

Thanks! Charlie

postgresql configuration missing in vagrant virtualbox installation

Posted: 04 Nov 2016 05:51 AM PDT

I'm by no means web developer, but I've lately tried to get some hang of the systems involved in this mystical field. I've gotten ok'ish grasp on ruby and rails/rake, but apparently setting up existing cloud based front/backend system in local development environment isn't really a piece of cake as I thought it would be :D.

So we've got rails backend and ReactJS front. The back is mounted to VirtualBox centos/7 virtual machine with vagrant using ansible cookbook.

So far I've got 2 issues and I think both are postgresql related.

  1. when I try to setup the vagrant, I get:

    fatal: [default]: FAILED! => {"changed": true, "cmd": "ls -A /var/lib/pgsql/9.4/data/postgresql.conf", "delta": "0:00:00.004547", "end": "2016-11-04 11:23:05.740650", "failed": true, "rc": 2, "start": "2016-11-04 11:23:05.736103", "stderr": "ls: cannot access /var/lib/pgsql/9.4/data/postgresql.conf: No such file or directory", "stdout": "", "stdout_lines": [], "warnings": []}

    the installation had just installed following postgres libraries: postgresql94-server, postgresql94, postgresql94-devel, python-psycopg2

    Due this there isn't psql server running in the virtual machine.

  2. If I try to run docker-compose api rake db:migrate, the system cannot connect to port I'm trying to use:

    Starting 5d9202af2e_5d9202af2e_backend
    ERROR: driver failed programming external connectivity on endpoint 5d9202af2e_5d9202af2e_backend(e31c0bd67d15fc074343f81058e1805527e6ac0884c0c7badd791284564bc0d1): Error starting userland proxy: listen tcp 0.0.0.0:5433: bind: address already in use

I've seem few threads about the 2nd case and they've normally just suggested that I should change the port. However I've tried that and it doesn't seem to matter. Also there isn't really anyone using that port.

My local machine is Ubuntu 16.04 with postgres 9.5 installed. The vagrant seems to install the 9.4, but I don't think this matters.

Any comments would be appreciated. I've read tons of threads regarding this matter from here and also looked both into vagrant and ansible. The big picture is still quite vague and there's not much documentation about this setup.

A workaround to pre-populate file_field?

Posted: 04 Nov 2016 06:26 AM PDT

I don't think you can literally pre-populate the file_field so I've been struggling with a workaround for the same end goal, which is to take an image already uploaded to the application via User A and then for User B to be able to save that same image as his own too, similar to pinterest.

This is what I've tried:

index

<%= link_to new_inspiration_path(inspiration_image: inspiration.image) %>

new

def new    @inspiration.image = inspiration_params[:inspiration_image]    @inspiration = current_user.inspirations.build  end  

server

Started GET "/inspirations/new?inspiration_image=%2Fsystem%2Finspirations%2Fimages%2F000%2F000%2F069%2Foriginal%2Frule_1.jpg%3F1478260961" for 127.0.0.1 at 2016-11-04 08:10:41 -0400  Processing by InspirationsController#new as */*    Parameters: {"inspiration_image"=>"/system/inspirations/images/000/000/069/original/rule_1.jpg?1478260961"} # For example, this is the image url I'm trying to duplicate for User B    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 129]]    Inspiration Load (0.4ms)  SELECT  "inspirations".* FROM "inspirations" WHERE "inspirations"."id" IS NULL LIMIT 1  Completed 400 Bad Request in 6ms  

_form

<%= simple_form_for(@inspiration, html: { data: { modal: true } }) do |f| %>     <%= image_tag @inspiration.image.url if @inspiration.image.present? %> # I get error: ActionController::ParameterMissing (param is missing or the value is empty: inspiration):    <%= f.file_field :image %>  <% end %>  

model

class Inspiration < ActiveRecord::Base    has_attached_file :image, :styles => { :medium => "300x300>", :small => "150x150>" }    validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]    belongs_to :user  end  

Value of cookies variable is not passing in another controller when using Mozilla Firefox in Rails

Posted: 04 Nov 2016 07:23 AM PDT

I am trying to set a cookies variable in users controller like
cookies[:uuid] = user.uuid
and then passing this to home controller like
@a = cookies[:uuid]
The value of cookies[:uuid] is getting passed in chrome but not in firefox. I checked in logs when using firefox value of cookies:[uuid] is nil. Why is this happening? Am I missing something?

Rails (bunny gem) RabbitMq : message lost from the queue when using pop function

Posted: 04 Nov 2016 05:19 AM PDT

I am using bunny gem to fetch data from rabbitMQ queue. i am using rabbitMQ "pop" function to get data from the queue and its working fine.

My issue is that whenever exception occurs inside the pop block my message is lost from the queue even if i have set manual_ack option set to true. for testing purpose i have manually raised the exception with code raise "excption" and can see the message is lost from the queue.

Below is my sample code.

  queue = c.queue(QUEUE_NAME, :durable => true)    exchange = c.topic(TOPIC_NAME, :durable => true)    queue.bind(exchange, :routing_key => "#{ROUTING_KEY_PREFIX}.#")      queue.pop(:manual_ack => true,:block => false) do |delivery_info, properties, payload|        raise "exception"        c.acknowledge(delivery_info.delivery_tag, false)      end  

How to avoid such lost of data from the queue when using pop function of bunny gem? is there alternative to pop function to prevent loss of data.

methode-missing error in rails when starting a server

Posted: 04 Nov 2016 06:34 AM PDT

Am new to rails, just going through a tutorial "learn ruby on rails" Have successfully push files/folders to the github repository.

I want to start the server with rails server to view the default home page of the rails app on my browser but I keep getting a NoMethodError.

I am running the command in my project directory "\projects\Rails\blog>",and i have installed all the required gems with the command "bundle install" after specifying Gem version as giving in the tutorial.

I have configured Rails to connect to email server ("Gmail") also. The error is as shown in the image below.

$ rails new learning    #creates a new rails project  $ git remote add origin https://github.com/MY_GITHUB_ACCOUNT/learning.git  $ rails generate figaro:install #To create application.yml file to hold  ENVs.  $ git push -u origin master  $ git add -A  $ git commit -m "add configuration"  $ git push  $ rails server  

How to check if jsonb column is empty Postgres

Posted: 04 Nov 2016 05:20 AM PDT

I am having trouble checking when the jsonb column of my table is empty.

My column directions when empty has value "{}"

Tried the following

Model.where("directions != '{}'") <- brings all  Model.where("directions <@ '{}'") <- brings all  

is there any other way that i am not aware of? Using postgresql 9.6

Rails custom action missing required key error

Posted: 04 Nov 2016 06:31 AM PDT

show.html.erb

<h1><%= @script.Name %></h1>    <%= simple_form_for @script , :url => script_execute_path do |f| %>    <%= f.input :mainDirectory %>    <%= f.input :customFilePath %>    <%= f.button :submit, 'Run' %>  <% end %>  

routes.rb

  root :to => "scripts#index"    resources :scripts do      get "execute"    end  

Model

class AddNameToScript < ActiveRecord::Migration    def change      add_column :scripts, :Name, :string      add_column :scripts, :Description, :text    end  end  

execute is a custom action added by me and I want to goto that action from show.

routes.rb

...      script_execute GET    /scripts/:script_id/execute(.:format) scripts#execute  ...  

But I am getting an error

No route matches {:action=>"execute", :controller=>"scripts", :id=>"1"}   missing required keys: [:script_id]  

But why do I need a [:script_id]? Isn't it a custom action and I can define the way I want? What's missing here and how do I pass [:script_id]?

1 comment:


  1. After reading this blog i very strong in this topics and this blog really helpful to all Ruby on Rails Online Course Hyderabad

    ReplyDelete