Sunday, July 31, 2016

Update many to to many relationship having ids | Fixed issues

Update many to to many relationship having ids | Fixed issues


Update many to to many relationship having ids

Posted: 31 Jul 2016 07:49 AM PDT

I have 3 model with many to many relationship:

Movie  Person  MovieToPerson  

Say I have a single person and I want to update the list of movies they star in. For movies I have ids. How can I do that?

pers = Person.first  movie_ids = get_movies_ids  pers.movies = ....????   

I want to avoid quiering the movie objects before updating.

Duplicating record isn't duplicating image

Posted: 31 Jul 2016 07:52 AM PDT

I'm trying to duplicate my record and using the amoeba gem. Everything copies fine except for the image (which is uploader via carrierwave)

For the image I tried doing a customized setting in amoeba like this:

amoeba do      customize(lamba { |original_object, new_object|          new_object.photo = original_object.photo      })  

but that just returned the path of the image still which when loading is looking in the individual record id.

How to create 1- and 2-dimensional hash

Posted: 31 Jul 2016 07:51 AM PDT

I am loading data from database and saving it to a constant like this:

profession = Hash.new  Profession.all.each do |p|    profession[p.name] = p.unique_profession    profession[p.name]['descr'] = p.description # problem    profession[p.name]['created_at'] = p.created_at # problem  end  

On the line profession[p.name]['descr'] occurs this error:

undefined method `[]=' for 1:Fixnum (NoMethodError)  

I want to use profession like:

<div>Profession name: <%= profession[p.name] %></div>  <div>Description: <%= profession[p.name]['descr'] %></div>  

How can I make profession work with as one [name] and as two [name][descr] parameters?

Path to a root file in controller

Posted: 31 Jul 2016 06:50 AM PDT

  1. Can you store a .pem as an environment variable? If so, how?
  2. How can I access my .pem from from the controller?

Controller:

before_filter :some_method    def show    @some_var = @data  end    private    def some_method      @data = Some::PrivateApplication.new(ENV['KEY1'], "../../secret.pem")    end  

Views:

<%= @som_var.SOMECONST.some_other_method %>  

No such file or directory @ rb_sysopen - ../../secret.pem

Activeadmin polymorphic association, paperclip attachments

Posted: 31 Jul 2016 05:59 AM PDT

I am using activeadmin for car resource and multiple attachments are not entering into records, car records are created successfully but on creation it did not contain attachment. I have two models 'Attachment', models/attachment.rb

class Attachment < ActiveRecord::Base      belongs_to :imageable, polymorphic: true        has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" },default_url: "/images/:style/missing.png"      validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/  end  

And and my model/car.rb contains following code

class Car < ActiveRecord::Base     has_many :attachments, as: :imageable     accepts_nested_attributes_for :attachments  end  

and in my app/admin/car.rb I have following code for multiple attachment.

form do |f|    f.input :make    f.input :model    f.input :color    f.input :engine_type    f.input :description    f.has_many :attachments do |attachment|      attachment.input :attachment, :as => :file    end    f.actions  end  

Can anybody please explain how to fix this issue?

Which page a record is on?

Posted: 31 Jul 2016 05:38 AM PDT

I want to have my pager start on the page for a given record and be able to page through the records before and after in the collection.

i get the code from here

https://github.com/amatsuda/kaminari/issues/205 and its working

when i put <%= @page_num %> on show.html.erb it give me the page number that the record is on

but i dont know how i can make it work in

     @page_num = @song.page_num(:per => 10)       @songs = @artist.songs.page(params[:page] || @page_num ).per(10)  

here is my model song.rb

class Song < ActiveRecord::Base    belongs_to :artist    extend FriendlyId  friendly_id :title, use: :slugged  friendly_id :title, :use => :scoped, :scope => :artist      def page_num(options = {})      column = options[:by] || :id      order  = options[:order] || :asc      per    = options[:per] || self.class.default_per_page        operator = (order == :asc ? "<=" : ">=")  (self.class.where("#{column} #{operator} ?", read_attribute(column)).order("#{column} #{order}").count.to_f / per).ceil    end    end  

songs_controller.rb

class SongsController < ApplicationController    def show      @artist = Artist.friendly.find(params[:artist_id])      @song = @artist.songs.friendly.find(params[:id])      @page_num = @song.page_num(:per => 10)      @songs = @artist.songs.page(params[:page] || @page_num ).per(10)         respond_to do |format|             format.html             format.js { render :layout => false }         end    end  end  

show.html.erb

<div id="songs-table">    <%= render 'songs' %>  </div>    <div id="songs-paginator" class="text-center">    <%= paginate @songs, :remote => true %>  </div>  

_songs.html.erb

<% @songs.each do |song| -%>  <%= link_to song.title, artist_song_path(@artist, song), class: "list-group-item#{' active' if @song==song}"  %>  <% end -%>  

show.js.erb

 $('#songs-table').html('<%= escape_javascript(raw(render 'songs')) %>');     $('#songs-paginator').html('<%= escape_javascript(paginate(@songs, remote: true)) %>');  

Rails: Accept optional nested Image; allow to add later if nil

Posted: 31 Jul 2016 07:09 AM PDT

I have a simple Article model associated with an Image model. The relationship is currently one-to-one (might change later but is fine for now).

Everything works fine when I create an Article from scratch and add an Image to it. Here's the catch: I would like the Image to be optional at creation, but also I would retain the option to add an Image at a later stage.

However, I am not sure how to handle that through the edit action. I have tried this:

  def edit      @article = Article.find(params[:id])      if @article.image.nil?        @article.image = Image.new      end      render 'articles/edit'    end  

... which results in:

ActiveRecord::RecordNotSaved in Admin::ArticlesController#edit

Failed to save the new associated image.

The form currently looks like this:

  <%= f.fields_for :image do |image| %>      <div class="form-group">        <%= image.label :image, "Article image" %><br/>        <%= image_tag(@article.image.path.thumb.url) %>        <%= image.file_field :path %>      </div>        <div class="form-group">        <%= image.label :caption %>        <%= image.text_field :caption, class: 'form-control' %>      </div>        <div class="form-group">        <%= image.label :credits %>        <%= image.text_field :credits, class: 'form-control' %>      </div>    <% end %>  

How can I accomplish optional nested images that can be added through the edit form later on?

Thanks!

How to add range filters in Rails?

Posted: 31 Jul 2016 06:06 AM PDT

I have a model Entry with attributes date and time. I want to add filters on index.html.slim with 4 input form:

1) start date 2) start time 3) end date 4) end time

And I want this form to find all records in this range.

.html.erb set div doesn't work correctly

Posted: 31 Jul 2016 03:45 AM PDT

I just created a scaffold in rails and list all stories in index page, and _stories.html.erb is partial which was rendered in index.html.erb

I want each story div has a red background for example:

.storyCell{      background-color:red;      height:100px;  }  

_stories.html.erb

<tbody>          <% @stories.each do |story| %>          <div class="storyCell">            <tr>              <td><%= story.content %></td>              <td><%= story.finished %></td>              <td><%= link_to 'Show', story %></td>              <td><%= link_to 'Edit', edit_story_path(story) %></td>              <td><%= link_to 'Destroy', story, method: :delete, data: { confirm: 'Are you sure?' } %></td>            </tr>          </div>          <% end %>        </tbody>  

But the result is the red div all in top of the story model properties. Thank you!

enter image description here

How to use Google::Auth::Stores::FileTokenStore.new for Google Calendar API

Posted: 31 Jul 2016 03:44 AM PDT

I'm trying to access the Google Calendar API from my Rails app.

The official guide is rather scarce, but I think I get most parts except for Google::Auth::Stores::FileTokenStore.new - what's the purpose of this and how should I use it in a traditional Rails app?

render an action from clicking a button without reloading page: Ajax

Posted: 31 Jul 2016 03:55 AM PDT

Im using ajax to make a controller action when clicked without reloading page. I cant seem to get the js view to be rendered.

transactions_controller:

require "braintree"        def index            @reservations = Reservation.where("transaction_id = transaction_id", true)        end        def escrow          @reservation = Reservation.find(params[:id])          @escrow = Braintree::Transaction.release_from_escrow(@reservation.transaction_id)          @reservation.update_attributes pay_completed: true          respond_to do |format|              format.html              format.js { render :layout=>false }          end       end        private      def reservation          @reservation = Reservation.find(params[:id])      end  

My link on index.html.erb:

<% @reservations.each do |reservation| %>  			<% @transaction = Braintree::Transaction.find(reservation.transaction_id) %>  			        <tr>    <td><%= reservation.id %></td>      <td><%= reservation.transaction_id %></td>      <td><%= reservation.reviser.user.username %></td>        <td><%= reservation.user.username %></td>      <td><%= @transaction.status %></td>      <td><%= @transaction.escrow_status %></td>      <td><%= reservation.created_at %></td>      <td><%= reservation.completed %></td>  <td><%= link_to "stock", escrow_path(reservation), :remote => true %></td>          </tr>      			    			    			    			<% end %>

routes.rb:

get 'admin/transactions' => 'admin/transactions#index'   patch 'admin/transactions/:id' => 'admin/transactions#escrow', :as => 'escrow'  

escrow.js:

$('#escrow').html("<%= j (render @escrow) %>");  

Im not sure what I am doing wrong! thank you! :)

i received this error 'Unpermitted parameter: image' in nested parameter

Posted: 31 Jul 2016 02:54 AM PDT

this is my profiles_controller.rb

 def create     @profile = current_user.build_profile(profile_params)      if @profile.save    else      render :new     end   end   end  

profile.rb has a nested attributes from image.rb

  params.require(:profile).permit(:first_name, :last_name, :phone_no, image_attributes: [:id,:image,:imageable_id,:imageable_type])  

This is profile.rb

 class Profile < ActiveRecord::Base   belongs_to :user   has_one :image , :as => :imageable   accepts_nested_attributes_for :image   end  

this is image.rb

  class Image < ActiveRecord::Base    belongs_to :imageable, polymorphic: true    mount_uploader :image, ImageUploader     end  

this is _form.html.erb from profile.rb model

   <%= f.fields_for :image do |ff| %>     <%= f.label :image %>     <%= f.file_field :image %>     <% end %>  

How to upload videos (resumably) to Vimeo from a Rails 5 app?

Posted: 31 Jul 2016 05:31 AM PDT

I am trying to upload videos to my Vimeo account from my RoR 5 application using the Vimeo API and the option "Resumable HTTP PUT uploads":

https://developer.vimeo.com/api/upload/videos#resumable-http-put-uploads

For this I'm using Paperclip to upload the video to my application and then I want to do a multipart PUT request to send the file with the Content-Length and Content-Type headers as the API documentation specifies, but I don't have an idea how to send the video file via PUT request, any help?

Thanks in advance.

Grab current users "admin" attribute from database

Posted: 31 Jul 2016 02:18 AM PDT

I have a Users model that has a field which is admin. This field is a boolean. I only want a user who is an admin (admin field = true) to be able to create a "Season." How on earth would I do this on rails? I don't even know where to start. I assume that in my application controller I could define "current_user_admin" and in my view use "current_user_admin?" to show the "create season" link. But what do I do in the model?

I do have current_user defined as such in my application_controller:

@current_user ||=User.find_by id: session[:user_id] if session[:user_id]  

Am I going down the right path? Any guidance is appreciated!

Rails 5: How to send and process large files (200Mb) via Rails API?

Posted: 31 Jul 2016 01:44 AM PDT

I'm looking for the general concept, but every tip can be useful. The client (mobile) has to send a large file to Rails API. It's a some text file with raw data.

How can the Rails API get the large file from client? Should it be done by HTTP request, websockets? Should the files be sent in chunks?

Why does have_selector "#MyId" fail when match /id=\"MyId\"/ passes?

Posted: 31 Jul 2016 02:23 AM PDT

I have a rails helper that generates a form

#helpers/my_helper.rb  def build_form     form_for object, url: object_path, method: :post do |f|      html = f.text_input :field      html += f.submit      html.html_safe    end  end  

And tests for this helper

#spec/helpers/my_helper_spec.rb  describe MyHelper do    it { expect( helper.my_helper ).to have_selector "form[action='#{objects_path}'][method='post']" } # PASSES    it { expect( helper.my_helper ).to have_selector "#object_field" } #FAILS - but this should pass    it { expect( helper.my_helper ).to match /id=\"object_field\"/ } # PASSES  end  

I am still learning rspec, so this may be an obvious question.

Why are these tests failing when using have_selector on the inputs. And yet have_selector correctly passes on the form tag, and match passes on the input ID.

jQuery.event.props is undefined

Posted: 31 Jul 2016 01:08 AM PDT

I'm using jquery.event.move to create move events on touch devices. The script is throwing an error on line 580.

570 // Make jQuery copy touch event properties over to the jQuery event  571 // object, if they are not already listed. But only do the ones we  572 // really need. IE7/8 do not have Array#indexOf(), but nor do they  573 // have touch events, so let's assume we can ignore them.  574 if (typeof Array.prototype.indexOf === 'function') {  575     (function(jQuery, undefined){  576         var props = ["changedTouches", "targetTouches"],  577             l = props.length;  578           579         while (l--) {  580             if (jQuery.event.props.indexOf(props[l]) === -1) {  581                 jQuery.event.props.push(props[l]);  582             }  583         }  584     })(jQuery);  585 };  

When it gets to line 580 it throws Uncaught TypeError: Cannot read property 'indexOf' of undefined The way I understand it is that jQuery.event.props is undefined? Shouldn't this array be present by default in jquery? I've "installed" jQuery in my rails app as a gem (jquery-rails 4.1.1) Any idea what I could do?

Rails 4 - Statesman - no method error

Posted: 31 Jul 2016 07:28 AM PDT

I have a model called organisation request. I have put statesman files on this model.

I have a couple of other models which I have also added statesman to and those work fine.

When I try to use this state machine, I get errors which say:

o = OrganisationRequest.last    OrganisationRequest Load (5.6ms)  SELECT  "organisation_requests".* FROM "organisation_requests"  ORDER BY "organisation_requests"."id" DESC LIMIT 1   => #<OrganisationRequest id: 1, profile_id: 40, organisation_id: 1, created_at: "2016-07-30 21:38:25", updated_at: "2016-07-30 21:38:25">   2.3.0p0 :137 > o.current_state  NoMethodError: undefined method `current_state' for #<OrganisationRequest:0x007f920bb21110>  

Can anyone see why?

 class OrganisationRequest < ActiveRecord::Base          include Statesman::Adapters::ActiveRecordQueries            # --------------- associations    belongs_to :profile      belongs_to :organisation      has_many :organisation_request_transitions, autosave: false        # --------------- scopes        # --------------- validations        # --------------- class methods      def state_machine      @state_machine ||= OrganisationRequestStateMachine.new(self, transition_class: OrganisationRequestTransition)    end       delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,             to: :state_machine            # --------------- callbacks      OrganisationRequest.after_transition(from: :requested, to: :approved) do |organisation_request, profile|      profile.organisation_id.update_attributes!(organisation_id: matching_organisation.id)        # add a mailer to send to the  user that is added to the org    end        OrganisationRequest.after_transition(from: :approved, to: :removed) do |organisation_request, profile|      profile.organisation_id.update_attributes!(organisation_id: nil)      end        # --------------- instance methods      # --------------- private methods      private        def self.transition_class        OrganisationRequestTransition      end        def self.initial_state        :requested      end    end  

Unable to permit additional parameters in device#accept invitation

Posted: 31 Jul 2016 12:58 AM PDT

I'm unable to permit additional parameters in "invite#accept". I've setup everything and here's a controller. But in the method "accept_resource" there're still only 3 old parameters accepted, other didn't come through, although they present on a form.

class MyInvitationsController < Devise::InvitationsController    before_filter :configure_permitted_parameters, if: :devise_controller?    before_filter :update_sanitized_params, only: [:edit, :update]      def edit      puts "edit...."      super    end      private      def accept_resource      puts "accept_resource..."      resource = resource_class.accept_invitation!(update_resource_params)        # but it still permits only :password, :password_confirmation and :invitation_token      resource    end      protected      def configure_permitted_parameters      puts "configure_permitted_parameters..."      devise_parameter_sanitizer.permit(:sign_up, keys: [:aaa, :bbb, :ccc, :password, :password_confirmation,                                         :invitation_token])      end      def update_sanitized_params      puts "update_sanitized_params..."        devise_parameter_sanitizer.permit(:sign_up, keys: [:aaa, :bbb, :ccc, :password, :password_confirmation,                                         :invitation_token])  

How to fix that? devise devise 4.2, devise_invitable 1.6

Updating Heroku database without deleting anything

Posted: 31 Jul 2016 12:46 AM PDT

I have my project in production right now using Heroku, but I want to add more tables and such to my rails database and than push it to Heroku. And I also plan on upgrading to Rails 5.

Are there any general rules that I should or shouldn't be doing so that my existing databases of Users does not accidentally get deleted?

Also, i noticed that Heroku has a 'backup' feature. Does this backup feature save a copy of all my Users information (email, name, pw, ect) which I can restore back at any certain time in case the unthinkable happens?

Getting real ip from Google Cloud Load Balancer and cloudflare

Posted: 30 Jul 2016 11:43 PM PDT

I want to get my real ip I'm using cloudflare and Google Cloud Network Load Balancer.

I have put this source to nginx.conf

# Last updated Sat Jul 30 11:17:32 UTC 2016  set_real_ip_from 103.21.244.0/22;  set_real_ip_from 103.22.200.0/22;  set_real_ip_from 103.31.4.0/22;  set_real_ip_from 104.16.0.0/12;  set_real_ip_from 108.162.192.0/18;  set_real_ip_from 131.0.72.0/22;  set_real_ip_from 141.101.64.0/18;  set_real_ip_from 162.158.0.0/15;  set_real_ip_from 172.64.0.0/13;  set_real_ip_from 173.245.48.0/20;  set_real_ip_from 188.114.96.0/20;  set_real_ip_from 190.93.240.0/20;  set_real_ip_from 197.234.240.0/22;  set_real_ip_from 198.41.128.0/17;  set_real_ip_from 199.27.128.0/21;  set_real_ip_from 2400:cb00::/32;  set_real_ip_from 2405:8100::/32;  set_real_ip_from 2405:b500::/32;  set_real_ip_from 2606:4700::/32;  set_real_ip_from 2803:f800::/32;  set_real_ip_from 130.211.0.0/22; #Google IP  real_ip_header X_Forwarded_For; #CF-Connecting-IP;  

To check my ip, I made simple rails source.

return render :json => {:ip => request.ip, :remote_ip => request.remote_ip, :x_forwarded_for => request.env['HTTP_X_FORWARDED_FOR'], :client_ip => request.env['HTTP_CLIENT_IP'], :cf => request.env['CF-Connecting-IP']}  

.

{"ip":"130.211.0.145","remote_ip":"130.211.0.145","x_forwarded_for":"(REAL IP), 141.101.85.141, 130.211.16.204, 130.211.0.145","client_ip":null,"cf":null}  

But ip was not my ip, it's Google Cloud LoadBalancer's. How do I fix this problem? I tried a lot of time over 6 hours.

Thanks.

ArgumentError in ContactsController#new

Posted: 31 Jul 2016 04:09 AM PDT

I am getting an error when I visit the page: localhost:3000/contacts

The error, details and the source code is provided below.

wrong number of arguments (1 for 2)

Extracted source (around line #4):

2  attribute :name,      :validate => true  3  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i  4  attribute :message  5  attribute :nickname,  :captcha => true  

model.rb

class Contact < ApplicationRecord    attribute :name,      :validate => true    attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    attribute :message    attribute :nickname,  :captcha => true      # Declare the e-mail headers. It accepts anything the mail method    # in ActionMailer accepts.    def headers      {        :subject => "HsbNoid",        :to => "iamhsb001@gmail.com",        :from => %("#{name}" <#{email}>)      }    end  end  

Code for controller

class ContactsController < ApplicationController       def new      @contact = Contact.new    end    def create      @contact = Contact.new(conact_params)      @contact.request = request      if @contact.deliver        flash.now[:notice] = 'Thank you for your message. We will contact you soon!'      else        flash.now[:error] = 'Cannot send message.'        render :new      end    end    private    def conact_params      params.require(:contact).permit(:name, :email, :message)    end  end  

Push object to s3 via aws ruby api v2

Posted: 30 Jul 2016 11:35 PM PDT

I'm trying to upload a file to amazon s3 but I'm getting the following error:

Aws::S3::Errors::PermanentRedirect: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.  

Here is how I'm doing it:

s3 = Aws::S3::Resource.new(    credentials: Aws::Credentials.new('xxxx', 'xxx'),    region: 'us-west-2'  )    obj = s3.bucket('dev.media.xxx.com.br').object('key')  obj.upload_file('/Users/andrefurquin/Desktop/teste.pdf', acl:'public-read')  obj.public_url  

I'm sure I'm using the right region, credentials etc..

What can I do ?

check current time is greater than defined time rails 4

Posted: 30 Jul 2016 11:51 PM PDT

I would like to check it my current time is greater than a defined time.

My start time could be anytime from day:

Like, Time.now.strftime("%I:%M %p") gives "11:17 AM"

I need to see if this time is greater than "04:00 PM" of same day

Means if any point my current time is greater than same day of 04:00 PM I have tried:

<%= distance_of_time_in_words(Time.now.strftime("%I:%M %p"), "04:00:00 PM") %>  

but its not working as expected.

any possible way to get this?

Plus please could anyone tell best practices as well to calculate the difference?

1 error prohibited this entity from being saved: Addresses entity must exist

Posted: 30 Jul 2016 11:25 PM PDT

can't able to save my entity.I have used nested_form gem and have permitted the addresses_attributes in entity_params but this error appears .please help me guys

1 error prohibited this entity from being saved:

Addresses entity must exist  

drop_table migration not working

Posted: 31 Jul 2016 03:36 AM PDT

Im having problems deleting a table that i created in migration.

executing rake db:migration VERSION=0 appears to be successful but looking at mysql the table is still present and schema.rb data is not removed.

def up  create_table :subjects do |t|      t.string "name"      t.integer "position"      t.boolean "visible", :default => false      t.timestamps   end  def down      drop_table :subjects  end  

Typo Edited: subject -> subjects

this happens only when i use def down. def change gives me no problem and deletes the table.

Turbolinks not ignoring page in Rails app

Posted: 31 Jul 2016 12:09 AM PDT

The front page view ('Welcome/index.html.erb') : https://github.com/bfbachmann/Blog/blob/master/app/views/welcome/index.html.erb

Rails Version: 4.2.6

The overarching problem:

I am trying to get my THREE.js model to show up properly inside my rails app. Everything works fine when I load the page by typing its URL into the search bar in my browser or if I hit reload or 'command' + R (on Windows its 'ctrl' + 'R') on my keyboard. I have a feeling this is because Turbolinks is not fired when these actions are performed. This leaves my model in the state it should be in as shown below.

HOWEVER... when I click one of the links in the navbar (blog, projects, about etc.) and then return to the home page by clicking the house icon either the rotation speed of the model doubles, or the model is duplicated. If the model is duplicated one copy stands still while the other rotates at its regular speed as shown below.

Broken Version Screenshot

What I've Tried

I have a strong feeling Turbolinks is to blame for this. So I tried to get Turbolinks to ignore that page by adding 'data-no-turbolink' to the body of that page... it didn't work. In fact I think Turbolinks was not even ignoring the page because it still loaded much faster when I clicked the home page link than when I re-entered the page's URL.

I tried adding a callback that would stop all the javascript responsible for the front page from running when the user navigates away from the page. This can be found in the view I linked at the top. I know this callback gets fired because I tested it. That also doesn't solve the problem.

Finally, I should also mention that I am using the JQuery-Turbolinks gem to resolve conflicts between the two.

Any help would be much appreciated. I have been trying to solve this problem for weeks.

Edit: I forgot to mention that I have read that Turbolinks has problems with inline javascript... this could be causing that problem.

Edit: It appears my javascript is being run every time I load ANY page on my site even though it is inline javascript. I can't understand why.

How to develop an API to make instant transfer from perfect money to payza/webmoney [on hold]

Posted: 30 Jul 2016 11:17 PM PDT

I'm looking for an API or library in Ruby or python or wordpress that can help me to develop an API to make instant transfer money between e-banks something like changer. Also if there is a guide to help me to do it and start a business in that field. Thanks in advance.

How whatsapp refreshes as soon as qrcode is scanned

Posted: 30 Jul 2016 10:39 PM PDT

How whatsapp actually refreshes the page as soon as the qrcode is scanned? Is it some sort of websockets or javascript? How to implement it on Ruby on Rails Kindly help ASAP

Error after removing column in database

Posted: 31 Jul 2016 07:11 AM PDT

I removed a column named assignment from my assignments database and encountered the following error:

enter image description here

assignments_controller.rb:

class AssignmentsController < ApplicationController      before_action :authenticate_user!      before_action :set_assignment, only: [:show, :edit, :update, :destroy]        # GET /assignments      # GET /assignments.json      def index          @assignments = Assignment.all      end        def mylist          @assignments = Assignment.where(user_id: current_user.id).find_each      end        # def bidders      #     @bids = Bid.where(bidders_params).find_each      #     #@bidders = User.where(user.id => @bids.user_id).find_each      #     @bids.each do |bid|      #         @bidders = User.where(user.id => bid.user_id).find_each      #     end      # end        # def bidders      #     idders_ids = Bid.where(bidders_params).pluck(:user_id)      #     @bidders = User.where(id: bidders_ids)      # end        # GET /assignments/1      # GET /assignments/1.json      def show      end        # GET /assignments/new      def new          @assignment = Assignment.new      end        # GET /assignments/1/edit      def edit      end        # POST /assignments      # POST /assignments.json      def create          @assignment = Assignment.new(assignment_params)            respond_to do |format|              if @assignment.save                  format.html { redirect_to @assignment, notice: 'Assignment was successfully created.' }                  format.json { render :show, status: :created, location: @assignment }              else                  format.html { render :new }                  format.json { render json: @assignment.errors, status: :unprocessable_entity }              end          end      end        # PATCH/PUT /assignments/1      # PATCH/PUT /assignments/1.json      def update          respond_to do |format|              if @assignment.update(assignment_params)                  format.html { redirect_to @assignment, notice: 'Assignment was successfully updated.' }                  format.json { render :show, status: :ok, location: @assignment }              else                  format.html { render :edit }                  format.json { render json: @assignment.errors, status: :unprocessable_entity }              end          end      end        # DELETE /assignments/1      # DELETE /assignments/1.json      def destroy          @assignment.destroy          respond_to do |format|              format.html { redirect_to assignments_url, notice: 'Assignment was successfully destroyed.' }              format.json { head :no_content }          end      end        private      # Use callbacks to share common setup or constraints between actions.      def set_assignment          @assignment = Assignment.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def assignment_params          params.require(:assignment).permit(:education_id, :subject_id, :gender_prefer, :timeslot, :duration, :budget, :budget_unit, :assignment_info, :user_id, :region_id)      end        def bidders_params          params.permit(:assignment_id)      end  end  

I'm well aware that it could be because of the .require(:assignment) in:

params.require(:assignment).permit(:education_id, :subject_id, :gender_prefer, :timeslot, :duration, :budget, :budget_unit, :assignment_info, :user_id, :region_id)  

I've tried changing that line to:

params.permit(:education_id, :subject_id, :gender_prefer, :timeslot, :duration, :budget, :budget_unit, :assignment_info, :user_id, :region_id)  

but to no avail.

Please help me on this matter. Thanks in advance!

Saturday, July 30, 2016

How to get posts with votes between two numbers? - Rails | Fixed issues

How to get posts with votes between two numbers? - Rails | Fixed issues


How to get posts with votes between two numbers? - Rails

Posted: 30 Jul 2016 08:00 AM PDT

I tried this, but it didn't work, it returns all posts

Post.where(' -1 < cached_votes_score < 10')  

although

Post.where(' cached_votes_score < 10')  

works, any thoughts on this?

Nested resource under users, I want only the current_user to be able to access

Posted: 30 Jul 2016 07:43 AM PDT

I have the following under my routes.rb:

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

I only want the current_user (the logged in user) to be able to see their own submitted_terms in terms of the index and show views. They shouldn't be able to see anybody else's index and show views and other people shouldn't be able to see theirs.

I think I know how to implement this but it feels sort of messy to me. Any thoughts?

Specificity issues with bootstrap

Posted: 30 Jul 2016 07:38 AM PDT

Why do I need !important for the margin:0 to show?

@import "bootstrap-sprockets";  @import "bootstrap";    .alert {    margin: 0 !important;  }  

and

 *= require_tree .   *= require_self  

Rails App behind Wordpress using fastcgi_intercept_errors

Posted: 30 Jul 2016 06:54 AM PDT

I'm starting a migration of a WordPress website to a rails application. The migration needs to be done gradually over the next few months, so I'll need to be able to run both sites in parallel. Using fastcgi_intercept_errors on a test environment I've managed to get any 404 errors returned by WordPress to forward on to the Rails application using the following configuration:

server {          listen 80 default_server;          listen [::]:80 default_server ipv6only=on;            server_name mydomain.com;          root         /var/www/html/wordpress;      index index.php index.html            error_page   500 502 503 504 404 @rails;        location / {          try_files $uri $uri/ /index.php?$args;          recursive_error_pages on;          error_page 404 = @rails;      }        location ~ \.php$ {                  fastcgi_pass unix:/run/php/php7.0-fpm.sock;                  fastcgi_index index.php;                  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;          fastcgi_intercept_errors on;                  include fastcgi_params;          error_page 404 = @rails;            }        location @rails{          passenger_enabled on;          passenger_user stephen;          rails_env development;          root /home/user/rails_app/app/public;      }  }  

The problem now comes when the rails app references any /assets links they always forward back into the rails app and always load the root location of the application.

Is there any way to fix this so that assets will also be treated as part of the rails application?

In Rails, Ajax sorting can't' keep up with User moving items around in my list

Posted: 30 Jul 2016 06:56 AM PDT

In my rails app I've made a list that allows the user to sort records by click/drag/dropping them to reorder. After each reorder I run the update action and pass along the old_index and new_index of the item moved and reorder the entire list. The application works as would expected as long as I don't reorder items at a very fast pace. My question is how can I improve the design I have to account for a quick paced sorting by the user and reflect those changes accurately? Also I'm trying to prevent the user from having to click a "Save" button -- however if it is necessary then I can implement that.

update action

      def update            if @list_item.present?              # update the modified item, and then update all items after that are affected            old_index = params[:old_rank].to_i            new_index = params[:sequence_rank].to_i              @list_item.update(sequence_rank: new_index) # update the moved item              # move element down and shift others up            if old_index < new_index              @list.list_items.where('sequence_rank <= (?) AND list_items.id \                <> (?) AND sequence_rank > (?)', new_index, @list_item.id, 0)                .each_with_index do |item,index|                item.update(sequence_rank: item.sequence_rank-1)              end            # move element up and shift elements down            else              @list.list_items.where('sequence_rank >= (?) AND list_items.id \               <> (?) AND sequence_rank < (?)', new_index, @list_item.id, old_index+1)               .each_with_index do |item,index|                item.update(sequence_rank: item.sequence_rank+1)              end            end            end            render nothing: true          end  

Also I'm using the following gem: https://github.com/scttdavs/sortable-rails

uninitialized constant ActiveModel::Observing (NameError)

Posted: 30 Jul 2016 06:44 AM PDT

I have developed a web application using ruby on rails. I have upgraded my rails version from 3.2 to 4.0 and I am getting the below error while starting my server.

Error :

/home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:11:in <module:Config>': uninitialized constant ActiveModel::Observing (NameError) from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:8:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:5:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid.rb:21:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:inblock (2 levels) in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:inblock in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:132:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/application.rb:88:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/environment.rb:6:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:3:inblock in ' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:in instance_eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:ininitialize' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in new' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:in eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:innew_from_string' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:40:in parse_file' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:277:inbuild_app_and_options_from_config' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:199:in app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:314:inwrapped_app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:250:in start' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:141:instart' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/bin/rackup:4:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:inload' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:in <main>' /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/ruby2.1.x/lib/ruby/site_ruby/2.1.0/amazon/brazil/ruby.rb:98:inexec_build_script': Command exited with status 1!! (RuntimeError) from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:61:in block in <main>' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:ineach' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:in `'

Can any one help me resolve this issue?

scroll bar with Lazy Highcharts

Posted: 30 Jul 2016 05:30 AM PDT

Hi I am relatively new to rails and I am trying to implement a horizontal scrollbar using the lazy highcharts gem. So far I am having trouble getting the scrollbar to work, any suggestions on what I am doing wrong/leaving out?

Controller:

@logsChart = LazyHighCharts::HighChart.new('graph') do |f|   f.series(:name=>'Session 2',:data=> [0, 20, 3, 5, 4, 10, 12 ])   f.series(:name=>'Session 1',:data=>[1, 3, 4, 3, 3, 5,4,-46,2,3,2,1,5,6,7,3,2,4,3,5,7] )    f.title({ :text=>"Load per Session"})   f.xAxis( min: 0,            max:12,           labels: {overflow: 'justify'})   f.scrollbar(enabled: true)   f.options[:chart][:defaultSeriesType] = "column"   f.plot_options({:column=>{:stacking=>"percent"}})  end  

View:

<%= high_chart("my_id", @logsChart) %>  

Gemfile:

gem 'lazy_high_charts', '1.5.0'  gem 'highstock-rails'  

application.js:

//= require highcharts  //= require exporting  //= require highcharts/highcharts  //= require highcharts/highcharts-more  //= require highcharts/highstock  

How do I display all attributes from a rails select statement?

Posted: 30 Jul 2016 06:36 AM PDT

Please would it be possible to know how to display the :user_id, :player_id and :amount attributes together in a hash from the below code?

At the moment the array created returns player_id as the key and amount as the value {1695=>100, 1714=>200} whereas I need something like {1695=>{:user_id,100}?

The code in the controller is as follows:

@duplicates = Bid.select(:player_id, :user_id, :amount).group(:player_id).having("count(*) > 1").maximum(:amount)  

The code in the view:

<div class="col-sm-3" style="background-color:white;">        <%= @duplicates %><br>    </div>  

Issue running rake task on azure server (via cloud66)

Posted: 30 Jul 2016 07:24 AM PDT

So i've got a cloud66 server (azure) running my web app

I'm trying to get the rake task to run on my webserver to populate my database (it runs fine locally)

Heres the error log im getting back

W, [2016-07-29T23:22:55.602769 #44674] WARN -- : Failed creating logger for file /var/deploy/appname/web_head/releases/20160729211819/log/newrelic_agent.log, using standard out for logging.    W, [2016-07-29T23:22:55.610222 #44674] WARN -- : Errno::EACCES: Permission denied @ rb_sysopen - /var/deploy/appname/web_head/releases/20160729211819/log/newrelic_agent.log    D, [2016-07-29T23:22:55.610373 #44674] DEBUG -- : Debugging backtrace:    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `initialize'    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `open'    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `open'    /usr/local/lib/ruby/2.2.0/logger.rb:628:in `open_logfile'    /usr/local/lib/ruby/2.2.0/logger.rb:584:in `initialize'    /usr/local/lib/ruby/2.2.0/logger.rb:318:in `new'    /usr/local/lib/ruby/2.2.0/logger.rb:318:in `initialize'  

Any ideas why this is failing?

How can i take a cut/commission in paypal?

Posted: 30 Jul 2016 05:05 AM PDT

how can i take a cut/commission in paypal after user has paid amount and before receiver has got amount.

In my application I allow sellers to give some service to customers. When a customer pays $100 to seller then I need to cut 12.5% as commission.

How can I do that in Paypal. My Application is in rails.

Brakeman Error - Unescaped model attribute near

Posted: 30 Jul 2016 07:08 AM PDT

I am getting a lot error as follows

Unescaped model attribute near line 20: show_errors(Objective.new(objective_params), :name)  

Expanded View

This is my code

module ApplicationHelper    # Error Helper for Form    def show_errors(object, field_name)      if object.errors.any? && object.errors.messages[field_name][0].present?        "<label class='text-error'>" + object.errors.messages[field_name][0] + "</label>"      else        return ""      end    end    end  

getting Missing Template error while creating a new user

Posted: 30 Jul 2016 04:50 AM PDT

Missing template admin/citizens/create, admin/application/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder, :rabl]}. Searched in: * "/Users/aa/Sites/Active Shehri/activeshehri-mongo/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/wiselinks-1.2.1/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/rails_admin-0.6.6/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/kaminari-0.16.1/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/devise_invitable-1.5.5/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/twitter-bootstrap-rails-3.2.2/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/devise-3.4.1/app/views"

.....here is the code

= form_for [:admin, @user] do |f|    .row      .col-lg-6        .panel          .panel-heading Edit Landmark          .panel-body            .form-group              = f.label :first_name              = f.text_field :first_name, class: 'form-control'            .form-group              = f.label :last_name              = f.text_field :last_name, class: 'form-control'            .form-group              = f.label :email              = f.text_field :email, class: 'form-control'            .form-group              = f.label :gender              = f.text_field :gender, :class => 'form-control'            .form-group              = f.label :contact_no              = f.text_field :contact_no, :class => 'form-control'            .form-group              = f.label :address              = f.text_field :address, class: 'form-control'          = f.submit 'Save', class: 'btn btn-primary btn-submit btn-lg pull-right'          = link_to "Back", admin_home_user_panel_path, class: 'btn btn-primary btn-submit btn-lg pull-left'  

How can I use the normal radio buttons in react?

Posted: 30 Jul 2016 03:53 AM PDT

I am developing a webapp which uses materializecss, react along with ruby on rails. I'd like to know how I can use the radio buttons such that it can be rendered.

    class Radio extends React.Component {          constructor(props) {    super(props);      this.state = {      }      this.setNewNumber = this.setNewNumber.bind(this)  };     setNewNumber(event)   {      this.setState({val : event.target.value})    }    render() {    return (         <div>          <input type="radio" name="gender" value="male" onChange={this.setNewNumber}/> Male<br/>          <input type="radio" name="gender" value="female"onChange={this.setNewNumber}/> Female<br/>          <input type="radio" name="gender" value="other"onChange={this.setNewNumber}/> Other          <p>Enter {this.state.val}</p>       </div>       );    }  }  

Rails 4 - 2 word model names

Posted: 30 Jul 2016 03:43 AM PDT

I'm using rails 4 with pundit and with statesman.

In each case, my pundit policy and my statesman model files don't work where the model name attached to them has two words.

For example, I have a model called organisation_request.rb

I have setup a pundit OrganisationRequestPolicy (in the same way I have set up every other pundit policy that applies to a model with a single word model name) and a state_tranistions file OrganisationRequestTransition (organisation_request_transition).

The pundit/statesman files don't work. The only difference I can see is that the model name has two words.

Is there a special convention for working with two word model names with these gems?

Capistrano deployed the app but its not opening in browser

Posted: 30 Jul 2016 02:56 AM PDT

I've a rails app that I'm trying to upload to a Digital Ocean (DO)'s droplet using capistrano, nginx and puma. I followed the tutorial in this link https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma and got the deployment part of the app to work. I didn't change much in my configuration files else than app name or changing server name in nginx.conf file to my droplet's ip. On deployment puma server starts. The trace messages are following:

Execute puma:start  04:35 puma:start        using conf file /home/root/apps/lixerr/shared/puma.rb        01 /usr/local/rvm/bin/rvm default do bundle exec puma -C /home/root/apps/lixerr/shared/puma.rb --daemon        01 RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,        01        01 you can ignore these warnings with 'rvm rvmrc warning ignore /home/root/apps/lixerr/current/Gemfile'.        01        01 To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.        01        01         01        01 Puma starting in single mode...        01        01 * Version 3.6.0 (ruby 2.3.0-p0), codename: Sleepy Sunday Serenity        01        01 * Min threads: 4, max threads: 16        01        01 * Environment: production        01        01 * Daemonizing...        01      ✔ 01 root@138.68.3.74 1.441s  

I checked the log files on my droplet, puma starts w/o showing any error messages. Moreever I also symlinked the nginx.conf to the sites-enabled directory and sites-available directory using:

sudo ln -nfs "/home/deploy/apps/appname/current/config/nginx.conf" "/etc/nginx/sites-enabled/appname"  

which they have mentioned at the end of the tutorial. Nginx is installed on droplet and I did not forget restarting it after creating the link. Still whenever I try to connect to droplet using its ip at http://138.68.3.74/ I get the following error in chrome:

This site can't be reached    138.68.3.74 refused to connect.  ERR_CONNECTION_REFUSED  

I've been working on it since last day and can't get it to work. I've no idea what am I missing.


EDIT 1: The log files of nginx in /var/log/nginx directory show nothing at all.

Checkbox "NoMethodError" in rails

Posted: 30 Jul 2016 03:27 AM PDT

I'm writing a CMS and I faced a problem while making a role management for users. I have a boolean field :admin in my User model, and I've made a checkbox in my form to set created user as an administrator. Here is the users_controller:

def create    @user = User.create(user_params)    respond_to do |format|      if @user.save        format.html { redirect_to users_path }        format.json { head :no_content }      else        format.html { render :new }        format.json { render @user.errors, status: :unprocessable_entity }      end    end  end    def edit  end    def update    respond_to do |format|      if @user.update(user_params)        format.html { redirect_to users_path }        format.json { head :no_content }      else        format.html { render :edit }        format.json { render @user.errors, status: :unprocessable_entity }      end    end  end  

and this is my form :

<%= form_for @user do |f| %>    # Here go fields for username, email and password    <p>      <%= f.label "Set as administrator" %> <br />      <%= f.hidden_field :admin, '' %>       # I also tried with <%= f.hidden_field :admin, false %>      <%= f.check_box :admin, checked = true %>       # Or <%= f.check_box :admin, data: { switch: true } %>    </p>  <% end %>  

But any of these options returns me the following:

NoMethodError in Multiflora::Users#edit    undefined method `merge' for "":String  

What have I done wrong?

Rails 4 - Mini_Magick doesn't work with images - don't see any resized pictures

Posted: 30 Jul 2016 05:33 AM PDT

I'm using Rails 4 + Carrierwave + Mini_Magick for image processing.

In my catalog all thumbnails are not displayed - "version :thumb" don't work.

In rails server log I see many routing errors like that:

Started GET "/uploads/item_image/image/57/thumb_testfile2.jpg" for ::1 at 2016-07-30 12:01:56 +0300  ActionController::RoutingError (No route matches [GET] "/uploads/item_image/image/57/thumb_testfile2.jpg"):  


When I change view partial from

...  = image_tag item.item_images.first.image.thumb.url  

to

...  = image_tag item.item_images.first.image.url  

fullsize images appear for all items!


How to fix that?

UPDATE

Mini_magick works only for pictures uploaded through form_for. When I upload items through my import-script - thumbs not generate

code from my import script:

folder="tmp/c_pics/"  path=folder + filename  new_image=ItemImage.new                           new_image.image = Rails.root.join(path).open  new_image.save!  curr_item.item_images << new_image  curr_item.save!  

I think that import script doesn't create thumbs during upload


Rails 4.2.6 + carrierwave 0.11.2 + mini_magick 4.5.1


Models

models/item.rb

class Item < ActiveRecord::Base      ...      has_many  :item_images      accepts_nested_attributes_for :item_images, :allow_destroy => true, reject_if: proc { |attributes| attributes[:image].blank? }  end  

models/item_image.rb

class ItemImage < ActiveRecord::Base      mount_uploader  :image, ImageUploader       belongs_to      :item  end  

Views

views/items/index.html.haml

%h1       All items  .items-list      = render "items_list"  %p      = link_to "Create new item", new_item_path(@item)  

views/items/_item_block.html.haml

%li      .pic          = image_tag item.item_images.first.image.thumb.url      .item_attr.name          = link_to item.name, item      .item_attr.price          price:          = item.price        .edit_control          = link_to "Edit Item", edit_item_path(item)  

views/items/_items_list.html.haml

%ul      - @items.each do |i|          = render "item_block", item: i  

Uploader

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base          include CarrierWave::MiniMagick          storage :file          def store_dir          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"        end          version :thumb do          process :resize_to_fit => [236, 236]        end          def extension_white_list          %w(jpg jpeg gif png)        end    end  

Database

db/schema.rb

...    create_table "items", force: :cascade do |t|    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.string   "name"    t.string   "model"    t.decimal  "price",      precision: 8, scale: 2  end    create_table "item_images", force: :cascade do |t|    t.string   "image"    t.string   "item_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    ...  

Gemfile

...  gem 'carrierwave'  gem "mini_magick"  gem 'rmagick'  

Console

results of "convert -version" command:

MacbookPro:eshop admin$ convert -version  Version: ImageMagick 6.9.3-7 Q16 x86_64 2016-03-27 http://www.imagemagick.org  Copyright: Copyright (C) 1999-2016 ImageMagick Studio LLC  License: http://www.imagemagick.org/script/license.php  Features: Cipher DPC Modules   Delegates (built-in): bzlib freetype jng jpeg ltdl lzma png tiff xml zlib  

results of "bundle show mini_magick" command:

MacbookPro:eshop admin$ bundle show mini_magick  /Users/aku/.rvm/gems/ruby-2.2.1/gems/mini_magick-4.5.1  

results of "bundle show rmagick" command:

MacbookPro:eshop admin$ bundle show rmagick  /Users/aku/.rvm/gems/ruby-2.2.1/gems/rmagick-2.15.4  

RoutingError (console - rails s)

Started GET "/uploads/item_image/image/57/thumb_testfile2.jpg" for ::1 at 2016-07-30 12:01:56 +0300    ActionController::RoutingError (No route matches [GET] "/uploads/item_image/image/57/thumb_testfile2.jpg"):  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'  web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'  rack (1.6.4) lib/rack/runtime.rb:18:in `call'  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'  railties (4.2.6) lib/rails/engine.rb:518:in `call'  railties (4.2.6) lib/rails/application.rb:165:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  rack (1.6.4) lib/rack/content_length.rb:15:in `call'  rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'  

Routing Error - No route matches [POST] "/xvaziris/125/hide"

Posted: 30 Jul 2016 03:32 AM PDT

Actually I wanted to hide the records on button click temporarily with carrying forward the running balance.

Please refer the screen-shot for better understanding as shown below;

image.png

When I clicked the "Hide" button, I keep running into the following error:

No route matches [POST] "/xvaziris/125/hide"

Please refer the screen-shot for better understanding as shown below;

screenshot.png

As I mentioned the method: :get in my partial but still it gives me the post routing error.

I tried running rake routes and I can see that the route exists:

C:\Users\pos1\Desktop\offorgs>bundle exec rake routes  DL is deprecated, please use Fiddle  DL is deprecated, please use Fiddle               Prefix Verb   URI Pattern                    Controller#Action                 root GET    /                              xvaziris#index         **hide_xvaziri GET    /xvaziris/:id/hide(.:format)   xvaziris#hide**             xvaziris GET    /xvaziris(.:format)            xvaziris#index                      POST   /xvaziris(.:format)            xvaziris#create          new_xvaziri GET    /xvaziris/new(.:format)        xvaziris#new         edit_xvaziri GET    /xvaziris/:id/edit(.:format)   xvaziris#edit              xvaziri GET    /xvaziris/:id(.:format)        xvaziris#show                      PATCH  /xvaziris/:id(.:format)        xvaziris#update                      PUT    /xvaziris/:id(.:format)        xvaziris#update                      DELETE /xvaziris/:id(.:format)        xvaziris#destroy      import_xvaziris POST   /xvaziris/import(.:format)     xvaziris#import                      GET    /xvaziris(.:format)            xvaziris#index                      POST   /xvaziris(.:format)            xvaziris#create                      GET    /xvaziris/new(.:format)        xvaziris#new                      GET    /xvaziris/:id/edit(.:format)   xvaziris#edit                      GET    /xvaziris/:id(.:format)        xvaziris#show                      PATCH  /xvaziris/:id(.:format)        xvaziris#update                      PUT    /xvaziris/:id(.:format)        xvaziris#update                      DELETE /xvaziris/:id(.:format)        xvaziris#destroy  xvaziri_resetfilter GET    /xvaziri/resetfilter(.:format) xvaziris#reset_filter  

routes.rb

Rails.application.routes.draw do          root 'xvaziris#index'        resources :xvaziris do          member do              get :hide          end      end        resources :xvaziris do           collection { post :import }      end          get '/xvaziri/resetfilter', to: 'xvaziris#reset_filter'    end  

xvaziris_controller.rb

class XvazirisController < ApplicationController      before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]          def index          @xvaziris = Xvaziri.find_by hidden: false          @xvaziris = Xvaziri.search(params[:search])            respond_to do |format|              format.js              format.html           end       end        def import          Xvaziri.import(params[:file])          redirect_to xvaziris_url, notice: "Xvaziris imported."      end        def show      end        def new          @xvaziri = Xvaziri.new      end        def create          @xvaziri = Xvaziri.new(xvaziri)          if              @xvaziri.save              flash[:notice] = 'Xvaziri Created'              redirect_to @xvaziri          else              render 'new'          end      end        def edit      end        def update          if @xvaziri.update(xvaziri)              flash[:notice] = 'Xvaziri Updated'              redirect_to @xvaziri          else              render 'edit'          end        end        def destroy          @xvaziri.destroy          flash[:notice] = 'Xvaziri was successfully destroyed.'          redirect_to xvaziris_url          end        def hide          @xvaziri = Xvaziri.find(params[:id])          @xvaziri.hidden = true          flash[:notice] = 'Xvaziri was successfully hidden.'          redirect_to xvaziris_url          end        def reset_filter          xvaziris = Xvaziri.all          xvaziris.each do |xvaziri|              xvaziri.hidden = false          end          redirect_to xvaziris_url      end        private      # Use callbacks to share common setup or constraints between actions.      def set_xvaziri          @xvaziri = Xvaziri.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def xvaziri          params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)      end    end  

index.html.erb

<div class="row">            <div class="col-md-10 col-md-offset-1">                <div class="table-responsive myTable">                    <table id = "kola" class="table listing text-center">                      <thead>                      <tr class="tr-head">                          <td>Description</td>                          <td>Amount</td>                          <td>Discount</td>                          <td>Paid</td>                          <td>Balance</td>                          <td>Button</td>                      </tr>                      </thead>                        <tbody>                                        <%= render @xvaziris %>                      </tbody>                      </table>                  </div>              </div>          </div>      <br>  <br>   <br>     <%= link_to "Show all", xvaziri_resetfilter_path %>  

_xvaziri.html.erb

<tr   class="tr-<%= cycle('odd', 'even') %>">        <td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>          <td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>          <% @balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = @balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(@balance.abs, :delimiter => ",", :precision => 2) %></td>        <td class="col-1"><%= button_to "Hide", controller: "xvaziris", action: "hide", id: xvaziri, method: :get %></td>    </tr>  

Any suggestions are most welcome.

Thank you in advance.

searchkick's autocomplete does not work on my iphone safari?

Posted: 30 Jul 2016 02:20 AM PDT

I've implemented elasticsearch/searchkick on my rails app and it works both in development and production on desktop browsers. But I noticed that the autocomplete does not work on safari on my phone. I reviewed the searchkick's docs and I've seen nothing about this issue. Anyone?

When I click on accept an invitation, I immediately get redirected

Posted: 30 Jul 2016 01:57 AM PDT

In my invitation controller I have this where I want to customize saving a user when they accept an invitation:

class InvitationsController < Devise::InvitationsController    before_filter :configure_permitted_parameters, if: :devise_controller?      private      def accept_resource      resource_class.accept_invitation!(update_resource_params)    end      def configure_permitted_parameters      #......  

When I click on accept an invitation, I immediately get redirected, it doesn't show me the "enter your new password" page:

Processing by InvitationsController#edit as   Redirected to http://localhost:3000/  Filter chain halted as :resource_from_invitation_token rendered or redirected  Completed 302 Found in 0ms (ActiveRecord: 0.0ms)  

I've tried to set this:

   config.allow_insecure_token_lookup = true  

but it throwed an exception at startup.

devise 4.2  devise_invitable   

How to create scaffold with many field relation from various two tables

Posted: 30 Jul 2016 04:43 AM PDT

I want to create a scaffold for table with below references. Heretransport_supervisor_id,manager_id,loading_supervisor_idthese things comes under user table references

  load_type_id (belongs_to load_type)    load_pick_from_date (date)    load_pick_to_date (date)    price (decimal presision 9,2)    transport_supervisor_id (belongs_to user)    manager_id (belongs_to user)    loading_supervisor_id (belongs_to user)    company_id (belongs_to company)  

How can i create like this? i want to create this rails g scaffolding command itself only.

Rendering another controllers action as a partial from another view in Rails

Posted: 30 Jul 2016 07:28 AM PDT

I am trying to render a partial (e.g in controllerA) from another controller (e.g controllerB), in my view. The partial is rendering correctly with static content but when trying to access an instance variable, it fails. The instance variable is instantiated by an action in controllerB but this action is never called when simply rendering the partial.

Is there a way to call an action before rendering the partial?

PG::InsufficientPrivilege: ERROR: must be owner of database

Posted: 30 Jul 2016 01:36 AM PDT

Good morning!

Faced with the problem that when you run the tests, swears that the error with the database owner, but just before given privileges to the user at the database with the tests, please tell me where to dig.

The test itself takes place, but before it pops up this error, username and database match the settings in the database.yml

I found a similar article, but I have another error, and this decision does not apply: ActiveRecord::StatementInvalid: PG::Error: ERROR: must be owner of database

Error Code: PG :: InsufficientPrivilege: ERROR: must be owner of database test

System:

Rails: 5.0.0

Ruby: 2.3.1

PSQL: 9.5.3

String.gsub in Ruby messing up the replacement?

Posted: 30 Jul 2016 04:22 AM PDT

This is a very unusual issue for me coming from JS background. I'm simply trying to replace a part of the page with external content on the fly.

Here is the source.html:

<!DOCTYPE html>  <html>    <head>      <%= foobar %>    </head>    <body>      This is body    </body>  </html>  

And a replacement string inject.js:

var REGEXP  = /^\'$/i; var foo = 1;  

Finally a ruby code that spits the output file by combining both.

pageContent = File.read('./source.html')  jsContent = File.read('./inject.js');  output = pageContent.gsub("<%= foobar %>", jsContent)  File.open('./dest.html', "w+") do |f|    f.write(output)  end  

However, I get the messed up dest.html which is happening because of \' in inject.js.

<!DOCTYPE html>  <html>    <head>      var REGEXP  = /^    </head>    <body>      This is body    </body>  </html>$/i; var foo = 1;    </head>    <body>      This is body    </body>  </html>  

How do I get rid of this naive issue?

Rails will_paginate with named scope for associations > 0

Posted: 30 Jul 2016 01:30 AM PDT

Similar to will_paginate with named_scopes but not getting an error - rather unexpected results. Rails version 4.

If I have a scope in a Foo model (where a user has_many: foos) - models/foo.rb:

belongs_to :user  scope :hasCars, -> { joins(:cars) }  

And now try use the scope with will_paginate (in the controller):

@foos = auser.foos.hasCars.paginate(:page=>1,:per_page=>20)  

Then the view duplicates each foo by the number of cars they have in the :through ownership association - so for foo 1 - 4 of a given user:

foo1.cars.size # =>1  foo2.cars.size # =>4  foo3.cars.size # =>0  foo4.cars.size # =>2  

View:

foo1  foo2  foo2  foo2  foo2  foo4  foo4  

Works as expected without the paginate and paginate works fine without the scope.

The association of Foo to cars is :through => :ownership. I guess it's to do with the way the scope is created using a join and how that join is passed to will_paginate. This is the query I see in the logs:

SELECT "".* FROM "foos" INNER JOIN "ownership" ON "ownership"."foo_id" = "foos"."id" INNER JOIN "cars" ON "car"."id" = "ownership"."car_id" WHERE "foos"."user_id" = ? [["user_id", 1]]

This should return the correct number of rows. But then for each car owned by Foo, I see a query cars from cars where foo_id = X being duplicated, am guessing from a query generated by will_paginate

Is there a better way to create the scope? Or should will_paginate be set up differently? Or could this be a will_paginate bug?

I have tried using joins(:ownership) too in the scope - same behaviour.

Make a copy of tenant in apartment gem

Posted: 30 Jul 2016 01:21 AM PDT

I am using apartment gem with PostgreSQL and I need to make a copy of already existing tenant with data. One way which I can think of one way is to collect all data from the tenant and then switch tenant and start creating record below is a small demonstration.models are the list of models to be copied over.

Apartment::Tenant.switch!('destination')  models.each do |modal|      eval("@#{modal.downcase} = #{modal}.all.collect{ |p| p.to_dh }")      end  Apartment::Tenant.switch!('target')  models.each do |modal|      eval("@#{modal.downcase}.each{ |p| #{modal}.create(p[:attributes], :without_protection => true) rescue p[:id]}")  end  models.each do |modal|  ActiveRecord::Base.connection.reset_pk_sequence!(eval("#{modal}.table_name"))         end  

Any help will be greatly appreciated.

not able to configure godaddy dedicated server

Posted: 30 Jul 2016 01:15 AM PDT

Hi I brought new godaddy dedicated server and changed named server and most of the settings. Installed nginx and unicorn server and my app data reside in /var/www/epiphanity location. But still my rails app is not working, nginx server is running properly

See the below screenshot what it shows. Struggling with this from last two days. I followed this tutorial, any help on this please.

How To Set Up Nginx Server Blocks on CentOS 7

enter image description here

Struggling to optimize rails WHERE NOT IN query in Rails

Posted: 30 Jul 2016 06:38 AM PDT

Here's the query as it is in rails:

User.limit(20).    where.not(id: to_skip, number_of_photos: 0).    where(age: @user.seeking_age_min..@user.seeking_age_max).    tagged_with(@user.seeking_traits, on: :trait, any: true).    tagged_with(@user.seeking_gender, on: :trait, any: true).ids  

And here's the output of EXPLAIN ANALYZE. Note the id <> ALL(...) part is shortened. There are around 10K ids in it.

Limit  (cost=23.32..5331.16 rows=20 width=1698) (actual time=2237.871..2243.709 rows=20 loops=1)    ->  Nested Loop Semi Join  (cost=23.32..875817.48 rows=3300 width=1698) (actual time=2237.870..2243.701 rows=20 loops=1)          ->  Merge Semi Join  (cost=22.89..857813.95 rows=8311 width=1702) (actual time=463.757..2220.691 rows=1351 loops=1)                Merge Cond: (users.id = users_trait_taggings_356a192.taggable_id)                ->  Index Scan using users_pkey on users  (cost=0.29..834951.51 rows=37655 width=1698) (actual time=455.122..2199.322 rows=7866 loops=1)                      Index Cond: (id IS NOT NULL)                      Filter: ((number_of_photos <> 0) AND (age >= 18) AND (age <= 99) AND (id <> ALL ('{7066,7065,...,15624,23254}'::integer[])))                      Rows Removed by Filter: 7652                ->  Index Only Scan using taggings_idx on taggings users_trait_taggings_356a192  (cost=0.42..22767.59 rows=11393 width=4) (actual time=0.048..16.009 rows=4554 loops=1)                      Index Cond: ((tag_id = 2) AND (taggable_type = 'User'::text) AND (context = 'trait'::text))                      Heap Fetches: 4554          ->  Index Scan using index_taggings_on_taggable_id_and_taggable_type_and_context on taggings users_trait_taggings_5df4b2a  (cost=0.42..2.16 rows=1 width=4) (actual time=0.016..0.016 rows=0 loops=1351)                Index Cond: ((taggable_id = users.id) AND ((taggable_type)::text = 'User'::text) AND ((context)::text = 'trait'::text))                Filter: (tag_id = ANY ('{4,6}'::integer[]))                Rows Removed by Filter: 2  Total runtime: 2243.913 ms  

Complete version here.

It seems like there's something wrong with Index Scan using users_pkey on users where the index scan is taking a very long time. Even though there's an index on age, number_of_photos and the id:

add_index "users", ["age"], name: "index_users_on_age", using: :btree  add_index "users", ["number_of_photos"], name: "index_users_on_number_of_photos", using: :btree  

to_skip is an array of user ids to not skip. A user has many skips. Each skip has a partner_id.

So to fetch to_skip I'm doing:

to_skip = @user.skips.pluck(:partner_id)  

I tried to isolate the query to just:

sql = User.limit(20).    where.not(id: to_skip, number_of_photos: 0).    where(age: @user.seeking_age_min..@user.seeking_age_max).to_sql  

And still getting the same problem with the explain analyze. Again, list of user ids is snipped:

Limit  (cost=0.00..435.34 rows=20 width=1698) (actual time=0.219..4.844 rows=20 loops=1)    ->  Seq Scan on users  (cost=0.00..819629.38 rows=37655 width=1698) (actual time=0.217..4.838 rows=20 loops=1)          Filter: ((id IS NOT NULL) AND (number_of_photos <> 0) AND (age >= 18) AND (age <= 99) AND (id <> ALL ('{7066,7065,...,15624,23254}'::integer[])))          Rows Removed by Filter: 6  Total runtime: 5.044 ms  

Complete version here.

Any thoughts on how I can optimize this query in rails + postgres?

EDIT: Here are the relevant models:

User model

class User < ActiveRecord::Base    acts_as_messageable required: :body, # default [:topic, :body]                        dependent: :destroy      has_many :skips, :dependent => :destroy      acts_as_taggable # Alias for acts_as_taggable_on :tags    acts_as_taggable_on :seeking_gender, :trait, :seeking_race    scope :by_updated_date, -> {      order("updated_at DESC")    }  end    # schema    create_table "users", force: :cascade do |t|    t.string   "email", default: "", null: false    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.text     "skips", array: true    t.integer  "number_of_photos", default: 0    t.integer  "age"  end    add_index "users", ["age"], name: "index_users_on_age", using: :btree  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree  add_index "users", ["number_of_photos"], name: "index_users_on_number_of_photos", using: :btree  add_index "users", ["updated_at"], name: "index_users_on_updated_at", order: {"updated_at"=>:desc}, using: :btree  

Skips model

class Skip < ActiveRecord::Base    belongs_to :user  end    # schema    create_table "skips", force: :cascade do |t|    t.integer  "user_id"    t.integer  "partner_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    add_index "skips", ["partner_id"], name: "index_skips_on_partner_id", using: :btree  add_index "skips", ["user_id"], name: "index_skips_on_user_id", using: :btree  

Evaluate the title is correct in the view (rendered)

Posted: 30 Jul 2016 01:45 AM PDT

I have an URL: http://myweb:2000/value.json. which display json array like

[{ id:1, t: "new"},{ id:2, t: "wel"}]  

Controller:

FactoryGirl.define do   factory :model_data do   id 1   t "MyString"  end    end  

Rspec code require 'spec_helper'

 describe "retrieve data" do   before(:all) do     DatabaseCleaner.start     @c1 = ModelData.new(id: '1', t: 'new')  end     after(:all) do       DatabaseCleaner.clean   end   it "returns no of objects" do  get 'value.json'  expect(JSON.parse(response.body)).to have(2).items  end  end  

controller code i have update. I am new to rspec please help.

rails redirect to edit page when submitting the form with the params of saved form

Posted: 30 Jul 2016 12:04 AM PDT

I'm new to rails,I've created a customer_details form.when I submit a form by clicking save button It should be saved and redirected to the edit page with all the contents of the form.so that i can download the form using download button.This is what im getting after saved the form

def create      @customer_detail = CustomerDetail.new(customer_detail_params)      @customer_detail.company_profile_id = current_user.company_profile.id      respond_to do |format|        if @customer_detail.save          format.html { redirect_to edit_customer_detail_path(@customer_detail), notice: 'customerDetails was successfully created.' }        else          format.html { render :new }        end      end    end  def edit     @customer_details = CustomerDetail.find(params[:id])    end
problem is,when I click save button it redirects to the edit path.but without any contents of form. what should I do now to get the form in edit_path?.can someone plz help me.thanks in advance!!