Friday, March 11, 2016

Rendering tables using bootsy WYSIWYG editor | Fixed issues

Rendering tables using bootsy WYSIWYG editor | Fixed issues


Rendering tables using bootsy WYSIWYG editor

Posted: 11 Mar 2016 06:41 AM PST

I would like to be able to add tables to the html content of a bootsy editor. I have enabled the html toolbar button. When I edit the html and add table tags and return to regular mode, the table tags get stripped and replaced by spans.

Devise install error rails application

Posted: 11 Mar 2016 06:40 AM PST

First time trying out devise. I added it to my gems but receive the following error message when I run $rails g devise:install. I also tried $ bundle exec rails g devise:install. I also looked in the routes.rb file, as others have suggested, and there is nothing there about devise.

Thanks in advance....Mitch

[!] There was an error parsing Gemfile: dependency name must be a String, was [, = 0">, 5.0">, = 1.3.0">, 4.1.0">, = 5.2, ~> 4.2">]. Bundler cannot continue.

# from /Users/charlesmcbee/Desktop/wyncodework/practice/movie_review/Gemfile:16 # ------------------------------------------- # # gem 'therubyracer', platforms: :ruby

gem gem 'devise', '~> 4.2', '>= 5.2' # # Use jquery as the JavaScript library # -------------------------------------------

Form not submitting as remote rails 3

Posted: 11 Mar 2016 06:33 AM PST

I am integrating a bootstrap theme into my rails 3 application, i have a form(Complicated form having multiple partials) defined as remote => true but that form is getting submitted as html.

However i tried to do the same for my login form with only 2 fields and it worked. I am confused as to what could be going wrong.

Can anyone please help.

Rails - object that belongs to multiple other objects

Posted: 11 Mar 2016 06:57 AM PST

Take the following associations based on a Feedback model:

feedback.rb

belongs_to :buyer, :foreign_key => :buyer_id, :class_name => "User"  belongs_to :seller, :foreign_key => :seller_id, :class_name => "User"  belongs_to :listing  

The reverse associations are has_many

When creating the feedback object it could be 'anchored' to any of the above other objects (e.g. buyer.feedbacks, seller.feedbacks, listing.feedbacks)


Say in this example we want to primarily link it with the buyer and so nest the feedback routes within user and then build a create action in the Feedbacks controller that looks something like:

current_user.feedbacks.new(feedback_params)  

or is it more appropriate/correct to reference?

buyer.feedbacks.new(feedback_params)    

Is this even valid without an explicit buyer model?


What is the Rails way to then incorporate the other belongs_to relationships?

It's not a nested attribute (as the other objects already exist).

Should I be merging in the other params with something like?

params.require(:feedback).permit(:rating, :comment).merge(seller_id: @seller.id, listing_id: @listing.id)  

One approach I have seen is the use of a before_validation filter in this sort of manner (from a different domain) like this:

class Feedback < ActiveRecord::Base    belongs_to :user    belongs_to :host, :class_name => "User"    belongs_to :inquiry    belongs_to :room    before_validation :set_room_and_guest_id    def set_room_and_guest_id    self.room ||= self.inquiry.room if self.inquiry    self.user ||= self.inquiry.user if self.inquiry  end  

I have spent a long time reading related posts about this today as well as the Rails documentation and have not been able to find a conclusion.

Trouble with accepts_nested_attributes_for in Rails 5.0.0.beta3, -api option

Posted: 11 Mar 2016 06:53 AM PST

I am using Rails 5.0.0.beta3, building an API-only app using the -app option on rails new, and I am having trouble with accepts_nested_attributes_for.

In my app, a create (or a new, then a save!) of an object with nested attributes fails, with a message that the parent parent object must exist.

To test, I made a new app and used just the test case with members and posts in the ANAF documentation:

class Member < ApplicationRecord      has_many :posts      accepts_nested_attributes_for :posts    end    

and

class Post < ApplicationRecord   belongs_to :member  end  

(These class definitions were generated by the Rails scaffold generator, so the inherit from ApplicationRecord, rather than ActiveRecord::Base, but per this post, that is not significant.)

With those classed defined, and matching migrations created and run, I launch a Rails console and follow the steps in the doc:

params = { member: {  name: 'joe', posts_attributes: [      { title: 'Kari, the awesome Ruby documentation browser!' },      { title: 'The egalitarian assumption of the modern citizen' },      { title: '', _destroy: '1' } # this will be ignored  ]}}      {:member=>{:name=>"joe", :posts_attributes=>[{:title=>"Kari, the awesome Ruby documentation browser!"}, {:title=>"The egalitarian assumption of the modern citizen"}, {:title=>"", :_destroy=>"1"}]}}  

And then:

>> member = Member.create(params[:member])   (0.2ms)  BEGIN   (0.4ms)  ROLLBACK  #<Member id: nil, name: "joe", created_at: nil, updated_at: nil>  

No joy!

When I split the create into new, then save!, I get the same result, with a somewhat clearer error:

>> member = Member.new(params[:member])    #<Member id: nil, name: "joe", created_at: nil, updated_at: nil>  

member.save!
(15.0ms) BEGIN ActiveRecord::RecordInvalid: Validation failed: Posts member must exist
from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/validations.rb:78:in raise_validation_error'
from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/validations.rb:50:in
save!' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/attribute_methods/dirty.rb:30:in save!' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/transactions.rb:324:inblock in save!' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/transactions.rb:395:in block in with_transaction_returning_status' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:233:inblock in transaction' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb:189:in within_new_transaction' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:233:intransaction' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/transactions.rb:211:in transaction' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/transactions.rb:392:inwith_transaction_returning_status' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/transactions.rb:324:in save!' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/activerecord/lib/active_record/suppressor.rb:45:insave!' from (irb):14 from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/railties/lib/rails/commands/console.rb:65:in start' from /Users/pauldavis/.rvm/gems/ruby-2.2.4 /bundler/gems/rails-b785064958f9/railties/lib/rails/commands/console_helper.rb:9:instart' (0.2ms) ROLLBACK from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/railties/lib/rails/commands/commands_tasks.rb:78:in console' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/railties/lib/rails/commands/commands_tasks.rb:49:inrun_command!' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/railties/lib/rails/command.rb:20:in run' from /Users/pauldavis/.rvm/gems/ruby-2.2.4/bundler/gems/rails-b785064958f9/railties/lib/rails/commands.rb:18:in' from /Users/pauldavis/Documents/Projects/Active/Rails/curious/doko/m.0/test_anaf/bin/rails:9:in require' from /Users/pauldavis/Documents/Projects/Active/Rails/curious/doko/m.0/test_anaf/bin/rails:9:in' from -e:1:in load' from -e:1:in'

Any thoughts on why this sample code in the documentation is be working? Could something be wrong in my environment? Does the -api option break something in ActiveRecord? BTW, I am using PostgreSQL

Thanks!

How to make factory_girl transient work with association?

Posted: 11 Mar 2016 05:58 AM PST

Previously I had a factory looking like this:

FactoryGirl.define do    factory :file do      ignore do        attachment_id 1      end        trait :file_with_autoplay do        type_key "file_with_autoplay"        attrs {{          "path" => attachment_id,          "volume" => 1        }}      end    end  end  

And when I built the factory using

create(:file, :file_with_autoplay, { story: story, attachment_id: attachment.id } )  

and it worked fine.

Now I had to refactor models a little bit. Before Story had File with columns type_key and attrs. Now File has one-to-one model Config, where I extracted type_key and attrs

So, my factory looks like this:

FactoryGirl.define do    factory :file do      ignore do        attachment_id nil      end        trait :file_with_autoplay do        association :config,          configuration_type: "file",          type_key: "file_with_autoplay",          attrs: {            "path" => "#{attachment_id}",            "volume" => 1          }      end    end  end  

So, not much changed, but I am passing attachment_id now to association. When I run the tests, I get

ArgumentError:     Trait not registered: attachment_id  

For clarity this is my new config factory:

FactoryGirl.define do    factory :config do      ignore do        attachment_id nil      end      configuration_type "file"      type_key "file_with_autoplay"      attrs {{        "generic_attr" => "generic_value"      }}    end  end  

What am I doing wrong here? How should I pass attachment_id transient through association in Factory Girl?

Rails 4: mail_to helper adds HTML attribute target="_blank"

Posted: 11 Mar 2016 06:14 AM PST

I am using mail_to helper method in the mailer views as follows,

mail_to "test@example.com", "Contact Us"

And it creates HTML as follows,

<a href="mailto:test@example.com" target="_blank">Contact Us</a>

This works fine as it opens default mailer application to draft the email.

But the issue is, due to it was added target="_blank" HTML attribute, unnecessary blank browser window opens.

I tried with no luck to find where it was added and how to prevent this. Please can anyone help out with this problem?

Removing folders from my rails app with rake [migrated]

Posted: 11 Mar 2016 05:50 AM PST

So I'm trying to remove the tmp/letter_opener folder. Everything works fine, just wondering if there's a better way to write it. My next step is to write some tests, to double check that I can only accept those inputs (currently failing)

#my_rake_task.rake    namespace :cleanup do    desc 'Deletes the emails inside tmp/letter_opener folder.'  task letter_opener_emails: :environment do    start_time = Time.current  Rails.logger.info "Task starting at #{start_time}."  puts "Task starting at #{start_time}."    print 'About to remove the tmp/letter_opener folder. Press [Nn] to abort. Press [Yy] to continue.'  option = STDIN.gets.strip    case option #[FIXME]: Not deleting the folders    when /[^Nn]/ then FileUtils.rm_r(Dir.glob('tmp/letter_opener/*'))      puts 'Directory contents removed'    when /[^Yy]/ then 'Exiting the task now.'       # abort_message  end  end  

Thanks in advance

Adding classes to fields in customized Rails form templates

Posted: 11 Mar 2016 06:39 AM PST

I'm trying to create a template to my Rails app forms using this recipe here, i.e., customizing the file lib/templates/erb/scaffold/_form.html.erb.

All I want is to make all the inputs with type="text" to have the same class="form-control", because I'm using Bootstrap 3.

Now, all these inputs are generated by this line in the template:

<%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>  

My problems are:

  1. I didn't understand completely the syntax of this line, what it is exactly saying, then it is hard to modify it according to my needs; and,
  2. I tried to substitute this line for other options, but none worked and I always get runtime errors.

May someone help me with some clue about what to do? Or at least explain me the systax of the line generating these inputs now, so I can continue myself?

Thanks in advance!

Change form_for submit label without changing passed parameter

Posted: 11 Mar 2016 06:53 AM PST

I have two submit button for my form_for: one is to save as draft, the other one is to publish. To deal with post's status (published or draft), I did this:

 <%= f.submit "published", class: 'form-control' name: "status"  %>   <%= f.submit "draft", class: 'form-control', name: "status" %>  

I pass the "status" parameter, and it takes as value either "published" or "draft". The issue is that the value is the label of the button. I'd like to change the label, but not the value. I tried to add:

label: "My label"  

to each button but didn't seem to work.

How could I do this ?

byebug and web-console not working in view

Posted: 11 Mar 2016 06:44 AM PST

In my Rails application, I am able to use byebug in controller. However, neither adding 'byebug' or 'console'[1] in view is helping me get to a debug console. I am using haml, thus it's not "<% console %>". In other words, the lines (one of the two at-a-time) I used in the view are:

byebug  console  

I haven't tried Pry or Pry-debug, but apparently they also don't work in views?

Am I using these gems incorrectly or is there another way to add debugs in views?

Thanks, Kumar

method on model returning empty during rspec tests even though it should have a value

Posted: 11 Mar 2016 05:22 AM PST

I am doing the following rspec test to test my '#clubs' method

context "#clubs" do    it "returns the users associated Clubs" do      club = create(:club)        user = club.host        expect(user.clubs).to contain(club)    end  end  

The method in my User model:

class User < ActiveRecord::Base    has_many :host_clubs, :class_name => 'Club', :inverse_of => :host    has_and_belongs_to_many :volunteer_clubs, :class_name => 'Club', :inverse_of => :volunteers      def clubs      [host_clubs, volunteer_clubs].flatten    end  end  

When I run the test and use p club.host, it returns the user as expected, however I cannot see why calling user.clubs => [] returns an empty array. Here is the factory for context.

factory :host, class: User do |f|    f.first_name { Faker::Name.first_name }    f.last_name { Faker::Name.last_name }    f.email { Faker::Internet.email }    f.password { Faker::Internet.password }    f.role { "host" }    f.onboarded_at { Date.today }      after(:create) do |host|      host.confirm_email_address    end  end    factory :club, class: Club do |f|    f.venue_type { "Primary school" }    f.name { Faker::Company.name }    f.address_1 { Faker::Address.street_address }    f.city { Faker::Address.city }    host  end  

Can anyone give me a heads up to why it may not be returning the record?

It's worth noting that I am adding this test after the method was created. In the console the method behaves as expected.

Build factories for self referential associations in rails

Posted: 11 Mar 2016 04:47 AM PST

I have a typical requirement, I have to address user object as follows

user.referrer and user.referrers.  

Basically, user can refer more than one person and one person should be referred by one particular user. So I build associations as follows. They are working great.

class User < ActiveRecord::Base      attr_accessible :account_number, :display_name, :referrer_id        has_many :referrers, :class_name => "User", :foreign_key => "referrer_id"      belongs_to :referrer, :class_name => "User", :foreign_key => "referrer_id"  end  

Now I would like to test assoications in Rspec. I am using factory girl so any one help me to build factories.

Active Admin pagination for array on custom page

Posted: 11 Mar 2016 04:40 AM PST

Im working on a custom active admin page that has a query to pull all records from two models in Rails and show them in most recent order. As a result, I get an array back.

Using that, Im trying to paginate it on the custom made page in active admin, that was made using their register_page method.

Relevant code for register_page

ActiveAdmin.register_page "Bookings" do     content do     table_for(((StudentAvailableSlot.all + StudentClass.all).sort_by {|obj| obj.created_at}).reverse!, class: 'index_table') do       #Display the information     end  

I cannot get ActiveAdmin to paginate the query and I've tried to get round it doing the following.

  1. Using Kaminari's paginate_array method but get this error: undefined method `except' for Kaminari::PaginatableArray
  2. Using active_record_union to maintain the ActiveRecord Relation class but it returned an array too.
  3. Creating a new model that could query both models and return a single collection with ActiveRecord Relation still available. I havent figured out how I would do this.

Any help would be greatly appreciated.

rails checking the existence of child objects

Posted: 11 Mar 2016 05:35 AM PST

I have a Rails 4 app. User has_one profile. When sby registers he/she is already a user, but he/she will have only profile after submitting profile form.

On my users page I would like to display all the users that have profile.

There are a few ways to display users with existing profile but I don't know which one is the preferred.

  1. Query in controller: loading only users w/ profiles

    @users = User.joins(:profile).includes(:profile)......  
  2. If profile.present? in view

    @users = User.includes(:profile).......      <% if user.profile.present? %>    <%= user.profile.first_name %>    ...........  
  3. Maybe there is an even better approach.

Can't get url for both images with rails and paperclip

Posted: 11 Mar 2016 04:22 AM PST

I have installed paperclip in my rails application, everything works fine but the problem is that I added two images for my Customer entity and when I return a Customer in the front-end (through API call) side I only get 1 url. This is the code:

Console log of the Customer entity:

Object {id: 2,  name: "carlos",  surname: "ruiz",  email: "carlos@car.com",  password_digest:"$2a$10$pJnjlXk5YUq0YrD5WhtmB.nDL3oeKo2U6S9JKSjhbfWf5ti6Ex6k2"…}  created_at: "2016-02-10T18:52:11.000Z"  email: "carlos@car.com"  header_path_content_type: "image/png"  header_path_file_name: "clients.png"  header_path_file_size: 1445943  header_path_updated_at: "2016-03-11T11:49:58.000Z"  image_path: "/system/customers/image_paths/000/000/002/original/earnings.png?1457696996"  image_path_content_type: "image/png"  image_path_file_name: "earnings.png"  image_path_file_size: 1587885  image_path_updated_at: "2016-03-11T11:49:56.000Z"  

As you can see I have the image_path path: /system/customers/... but I don't have the header_path path, just the content, the file size, name and date.

Here is the model:

  class Customer < ActiveRecord::Base      ...      has_attached_file :image_path, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/user_images/missing.png"      has_attached_file :header_path, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/user_headers/missing.png"      validates_attachment_content_type :image_path, content_type: /\Aimage\/.*\Z/      validates_attachment_content_type :header_path, content_type: /\Aimage\/.*\Z/    end  

Migration:

class AddUserPhoto < ActiveRecord::Migration      def up      add_attachment :customers, :image_path      add_attachment :customers, :header_path    end      def down      remove_attachment :customers, :image_path      remove_attachment :customers, :header_path    end  end  

The strange thing is that in the console and in the back-end admin part I can upload and see both images, and if I type Customer.first.header_path in the console I can see the correct path. But when I send the Customer through the api I have this problem. Here is the function that return the customer:

  def client_details      hairdresser_id =  params[:api][:hairdresser_id]      token =           params[:api][:token]      customer_id =     params[:api][:customer_id]        if token.nil? or token.empty?        render :json => {:error => "not authorized"}      end        if allowed_customers_id.include? customer_id.to_i        customer = Customer.find customer_id          render :json => {          :customer_details => customer,          :customer_addresses => customer.addresses,          :customer_note => note,          :customer_appointments => Appointment.where(:customer_id => customer.id).reverse,          :appointment_services => Appointment.where(:customer_id => customer.id).where.not(:status => 'cancelled').map{|app| app.service_appointments.first.service.name}.reverse,          :error => ''        }      else        render :json => {:error => 'Not authorized'}      end    end  

Do you know what am I missing?

rails wash_out gem output

Posted: 11 Mar 2016 04:54 AM PST

I'm trying generate this output.

<complexType name="KitProduto">`  <sequence> `  <element maxOccurs="1" minOccurs="0" name="MsgRet" nillable="true" type="xsd:string"/>  <element maxOccurs="1" minOccurs="0" name="NomProduto" nillable="true"  type="xsd:string"/>   <element maxOccurs="1" minOccurs="0" name="CMPObrig" type="xsd:string"/>   <element maxOccurs="1" minOccurs="0" name="CMPAjuda" type="xsd:string"/>   </complexType>   <complexContent>   <attribute ref="soapenc:arrayType" wsdl:arrayType="tns1:KitProduto[]"/>   </complexContent>   

thanks

Ruby on Rails: Prevent users back to login form after logged in successfully

Posted: 11 Mar 2016 05:29 AM PST

Ok. I have a login page. After I entered the email and password correctly and it redirects to me to the user profile. When I hit the browser back button, it also redirects to the user profile which works fine. But the problem raises when let's say if I enter the email or password wrongly, it says "email/password incorrectly", and I enter second time correctly it redirects me to the user profile, but when I hit the browser back button, the page will show "Comfirm form resubmission". This doesn't make sense.

backend with ajax to detect if user is no longer active

Posted: 11 Mar 2016 04:26 AM PST

I'm trying to create a heartbeat that runs at a set interval, to make sure the user is still on the page. Which I've done:

(function worker() {    $.ajax({      type: 'POST',      url: '/users/' + <%= current_user.id %> + '/heartbeat',       success: function(data) {        console.log('updated')      },      complete: function() {        setTimeout(worker, 5000);      }    });  })();  

now what I'd like to do on the backend is change the status to current_user.inactive! if it doesn't receive an update for say 30 seconds. I'm assuming a lot of you have done something similar in an app, and I want to get a feel for the best way to do this?

Is it to have it update a column in the DB and have a background job constantly running? or is there some much more efficient way?

Rails: process partials with loop, add additional class for the first item

Posted: 11 Mar 2016 04:09 AM PST

I'm trying to implement some kind of image gallery. And I decided to use partials with an image snippet inside. For each image category the partail is added 5 times per page. Actually it's pretty easy:

# main page  .container    .row      .col-lg-12        %h1.page-header Image Gallery      - 5.times do        = render partial: 'image'    # partial  .col-xs-6.col-md-2    = link_to image_tag('http://placehold.it/128x128', class: 'img-responsive'), '#', class: 'thumbnail'  

But the problem is the first div in a row should have an additional class .col-md-offset-1 (I have an odd number of images per the page). I doubt this can be done inside the cycle. Does anyone know how this can be workarounded?

Server rendering with rails + react-rails gem + react router

Posted: 11 Mar 2016 04:41 AM PST

I have create this sample repo that use rails (v4.2.6) with react-rails (v1.6.2) and react-router (v2.0.0-rc5): https://github.com/pioz/rails_with_react_and_react_router_example

In the file app/views/application/react_entry_point.html.erb I render the component MountUp with

<%= react_component('MountUp', {}, {prerender: false}) %>  

The component MountUp render my router:

class MountUp extends React.Component {    render() {      return(        <Router history={History}>          <Route path="/" component={App}>            <IndexRoute component={Index} />            <Route path="/contact" component={Contact}/>            <Route path="/about" component={About}/>          </Route>        </Router>      )    }  }  

All works fine, but if I change the option prerender: true I get a strange error React::ServerRendering::PrerenderError in Application#react_entry_point:

Encountered error "Error: Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." when prerendering MountUp with {}  Object.invariant [as default] ((execjs):21983:16)  createHashHistory ((execjs):24108:130)  (execjs):22633:20  wrapDeprecatedHistory ((execjs):25285:61)  createRouterObjects ((execjs):25259:23)  componentWillMount ((execjs):25228:38)  ReactCompositeComponentMixin.mountComponent ((execjs):8138:13)  wrapper [as mountComponent] ((execjs):3131:22)  Object.ReactReconciler.mountComponent ((execjs):6583:36)  ReactCompositeComponentMixin.mountComponent ((execjs):8153:35)  /Users/pioz/.rvm/gems/ruby-2.3.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:39:in `exec'  ...  

How can I render this app server side? Is this the right way to do this?

Different behavior of TCPSocket with rails app

Posted: 11 Mar 2016 04:49 AM PST

i have a problem on one of my rails app developpement. I use heroku to deploy my rails app (prod env). And i have a misunderstanding between dev and prod environnemnt.

When i excecute "require 'socket'; TCPSocket.new(nil, 80)" in my rails console in dev env (rails console, on my computer in local) and the same commande in the rails command of heroku (heroku run rails console), i don't have the same result.

In dev env, i get "#TCPSocket:fd 18" then no problem occured but in prod env i get "Errno::ECONNREFUSED: Connection refused - connect(2) for nil port 80

from (irb):1:in initialize' from (irb):1:innew'

from (irb):1

from /app/vendor/bundle/ruby/2.3.0/gems/railties 4.2.5/lib/rails/commands/console.rb:110:in `start'

from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/console.rb:9:in `start'

from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:68:in `console'

from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'

from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `'

from /app/bin/rails:9:in `require'

from /app/bin/rails:9:in main "

I have the same environnment (same version of ruby, rails, etc...) So, if one of you as already met the problem before or could explain me the behavior of TCPSocket in that case.

Thank you in advance.

Paperclip / AWS-SDK Uninitialized Constant Aws::S3::Errors

Posted: 11 Mar 2016 03:00 AM PST

I've been pulling my hair out all morning trying to fix this, and have consulted every other SO post about Paperclip/AWS issue, but none of the fixes described in them seem to apply to my situation.

Whenever I try to upload an image to S3 with Paperclip configured to use S3 storage, I get the following exception:

A NameError occurred in CONTROLLER_NAME#ACTION:    uninitialized constant Aws::S3::Errors  /home/deployer/sites/ws-prod/shared/bundle/ruby/1.9.1/bundler/gems/paperclip-523bd46c7682/lib/paperclip/storage/s3.rb:412:in  `rescue in block in flush_writes'  

Paperclip config works fine locally, as well as in the production server's rails console (e.g., defined?(Aws::S3::Errors) returns "constant").

Gemfile

gem "rails","3.2.3"  gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git  gem 'aws-sdk-v1'  gem 'aws-sdk', '~> 2'  

Model

require 'aws-sdk-v1' # these were just added to test whether initialization issues were at fault  require 'aws-sdk'    has_attached_file :cover,    :storage => :s3,    :styles => {      :thumb => "120x160>"    },    :s3_credentials => {      :access_key_id => S3Config.config[:access_key_id],      :secret_access_key => S3Config.config[:secret_access_key]    },    :s3_region => S3Config.config[:region],    :s3_permissions => 'public-read',    :bucket => 'name.of.s3.bucket',    :preserve_files => "false",    :dependent => :destroy  

I've tried reverting to aws-sdk-v1, but I get the same exception when I try to use the app to upload assets to S3.

Anyone else having this issue??

ruby : regex replace string beetween two char [ ]

Posted: 11 Mar 2016 05:57 AM PST

i want to remove text in string beetween [ ]: ex:

Hello everyone [hi hi], hello world [ha ha]  

result:

Hello everyone, hello world  

i use

string.gsub!(regex-here , ' ')  

help me define a regex-here.

How to call Rails console on server, if it uses Mina?

Posted: 11 Mar 2016 02:52 AM PST

Before implementation Mina on server, I called it with:

rails console  

now I get:

-bash: rails: command not found  

How can I call it now?

Rails activerecord query with has_many belongs_to association

Posted: 11 Mar 2016 04:00 AM PST

I have two ActiveRecord models: User and Course. Which are associated as following:

class User < ActiveRecord::Base    has_many :courses  end    class Course < ActiveRecord::Base    belongs_to :user  end  

Now my question is: how can I get the last course of each user?

I tried following:

courses = Array.new  User.find_each { |u| courses << u.courses.last }  

But I'm doubt on its performance. So looking for best solution with good performance.

Thanks in advance.

Rails. Count records that have a specific attribute:string

Posted: 11 Mar 2016 02:34 AM PST

I have a model with a string attribute. This attribute (status) is updated to seen, notseen, hired, and reject depending on certain variables within my app.

I would like to count all records where status != reject.

Looking at the docs here it looks like it should be something like;

<%= Mymodel.count(:conditions => [ "status = ?", 'reject' ]) %>  

but this is not correct, it returns a count of all instances regardless of status.

How can I achieve this?

ActiveAdmin: how to add formatter to any column with specific name?

Posted: 11 Mar 2016 02:49 AM PST

I have a helper called ip_with_location which translates 10.10.10.10 to 10.10.10.10 - DE, Berlin form.

Usage example:

index do    ...    column :ip do |r|      ip_with_location(r.ip)    end  end  

The questions is: Is there a way to automatically format column value with my custom helper?

So I would just write column :ip instead.

Overwriting ip getter on model level would not be an option, cause i want such format only in ActiveAdmin

Rails - What is the best way to display default avatar if user doesn't have one?

Posted: 11 Mar 2016 02:29 AM PST

Right now, each time I need to display a user's avatar, I have if statements that check whether they uploaded an avatar or not. I know it's definitely not DRY if I have these statements littered through my html.

So, what's the best way to find out which image to display?

Edit: I'm using Carrierwave (Paperclip didn't work for me for some reason)

has_one and has_many relationships to the SAME object type

Posted: 11 Mar 2016 02:16 AM PST

I'm writing a website using Ruby on Rails and I have a number of polymorphic relationships but I want two particular relationships that are:

A has_one C  B has_many C  

When I generate the polymorphic code for C using Rails it seems that the has_one A/C relationship expects functions of form:

A.C... e.g.  @c = @poly.c.find(params[:id])  

whilst the has_many B/C relationship expects functions of form

B.Cs... ** Note the plural for B **  @c = @poly.cs.find(params[:id])  

So is there a way to do what I want or do I have to make the A/C relationship has_many and add additional checking to ensure that it acts like has_one?

No comments:

Post a Comment