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!

No comments:

Post a Comment