Sunday, November 20, 2016

How to sort ActiveRecord Relation results on a custom logic? | Fixed issues

How to sort ActiveRecord Relation results on a custom logic? | Fixed issues


How to sort ActiveRecord Relation results on a custom logic?

Posted: 20 Nov 2016 07:37 AM PST

I have a table containing a number of location objects(columns are id, latitude and longitude). I select rows from this table based on some query, then for these results, I want to find the distance of each location (using latitude and longitude of this point) from a custom point. How do I sort it on a manual logic? Here is what I tried:

# Location Model    def self.search(params, fields, user, employee_id)      marker = SearchHelper.change_to_point(params[:marker_distance_sort])        results = self.select(columns_selected)              .intersect_query(boundary)        # What should I do here for custom sorting?      results.sort_by { |a, b| a.distance_from_marker(marker) <=> b.distance_from_marker(marker)}    end    def self.distance_from_marker(marker)      marker.distance(FACTORY.point(self.attributes['longitude'], self.attributes['latitude']))  end  

Sorry I am really new to ruby on rails and I have tried every resource available on stack overflow answers for custom sorting. Thanks for the help!

Angular 2 + Rails + Auth0

Posted: 20 Nov 2016 07:04 AM PST

I'm trying to figure out how to use Auth0 with an Angular/Rails application.

I've set up Auth0 with an Angular-only application and it worked fine. I can see the Auth0 docs for Rails and as far as I can tell it makes sense.

What I don't understand is how to connect the front-end authentication with Rails, since I'm not finding documentation on this anywhere.

Rails - Does this Rails method acquire a lock?

Posted: 20 Nov 2016 06:25 AM PST

Let's say there's no connections available in the connection pool, and I'm doing this

ActiveRecord::Base.connection_pool.with_connection do  ...  end  

Will this method acquire a lock and only continue when some connection has been released?

Ruby on Rails MySQL issues on Sierra/El Capitan Mac

Posted: 20 Nov 2016 06:19 AM PST

Updated OS to El Capitan and then to Sierra. Now when working on an old Ruby on Rails project, all of sudden rails cannot get the data from relevant tables.

I have reinstalled Homebrew, mysql, rails, ruby, and xcode is updated with CLI installed.

I have backed up the old database which was working before and imported back into a brand new installation of mysql. Rails logs in correctly to the project (which was not doing it before) but after that getting index pages fails with 'reorder' problem for nil class.

Started GET "/admin/buildings" for 127.0.0.1 at 2016-11-20 08:36:21 -0500  Processing by Admin::BuildingsController#index as HTML    AdminUser Load (0.3ms)  SELECT `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 2 LIMIT 1    Rendered /Users/mh/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activeadmin-0.6.2/app/views/active_admin/resource/index.html.arb (25.5ms)  Completed 500 Internal Server Error in 38.0ms    ActionView::Template::Error (undefined method `reorder' for nil:NilClass):      1: insert_tag renderer_for(:index)  

brew version Homebrew 1.1.1 Homebrew/homebrew-core (git revision 421e; last commit 2016-11-20)

ruby version (via rbenv) ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]

rails version Rails 3.2.22.5

mysql version Server version: 5.7.16 Homebrew

Hopefully not a duplicate (I have searched), but apologies if it is.

How to set group by for SUM of specific column rails

Posted: 20 Nov 2016 07:10 AM PST

I have below query:

@play_lists_progress.sorted_resource.quiz_attempts.select("quiz_attempts.*,   SUM(quiz_attempts.score) as user_count").group("quiz_attempts.id,   quiz_attempts.student_id")  

whose sql is:

SELECT quiz_attempts.*, SUM(quiz_attempts.score) as user_count FROM   "quiz_attempts" WHERE "quiz_attempts"."quiz_id" = 3 GROUP BY   quiz_attempts.id, quiz_attempts.student_id  

and results are:

enter image description here

How it could be like:

quiz_id  student_id   score     3       1           26.6  

Rails User add friend through HTTP request

Posted: 20 Nov 2016 06:10 AM PST

So I have a User model (don't we all? :D) in my Rails application. A User can add friends.

I am following the answers given here: Model design: Users have friends which are users

User.rb

class User < ApplicationRecord    ...    has_and_belongs_to_many :friends,      class_name: "User",      join_table: :friends_users,      foreign_key: :user_id,      association_foreign_key: :friend_id      ...  end  

I have generated my migration file using:

rails generate CreateFriendshipJoinTable users friends  

The resulting migration file with some modification:

Migration File

class CreateFriendshipsJoinTable < ActiveRecord::Migration[5.0]    def change      create_join_table :users, :friends do |t|        t.index [:user_id, :friend_id]        t.index [:friend_id, :user_id]      end    end  end  

Update Action

def update      user = User.find_by({id: params[:id]})        skip_authorization and render status: :not_found and return unless user        authorize user        attributes = policy(User).permitted_attributes_for_update        if user.update_attributes!(params.permit(attributes))          render json: user      else          render status: :unprocessable_entity      end  end  

Test

  test "user friends - should successfully add a friend" do      put user_path(@jim), params: {user_id: @sarah.id}, headers: user_authenticated_header(@jim)      assert_response :success        json = JSON.parse(response.body)      puts "json = #{json}"        user = User.find_by({id: @jim.id})      assert_includes user.friends, @sarah    end  

My test fails.

I am not sure what the parameter to the HTTP PUT request is to tell my User the "friend" id is some number and that my User update action should find other User using given friend id and add that user as a friend of first user.

I am however, able to use rails console --sandbox successfully to add friends by creating two users, then using this code:

jim.friends << sarah  

This adds Sarah as a friend of Jim as expected, which leads me to believe my table relationship is...half...working?

Any ideas anyone? :D

send_file in rails 5 stopped the browser from downloading

Posted: 20 Nov 2016 06:56 AM PST

after upgrading to Rails 5, sending a file using:

send_file file_url, :type=>"application/pdf", :x_sendfile=>true, disposition: params[:disposition]  

stopped downloading the file, instead, it opens the following like window (same window)

enter image description here

Rails 4.2.4 - dynamic menus in simple form with associations

Posted: 20 Nov 2016 05:44 AM PST

I want to populate one selection field based on choice from other selected field. It's about categories / subcategories, when user is trying to submit new product. User picks main category in field 1, after picked main category he gets option to pick from field 2 children subcategories of picked main category from field 1. It's based on associations so it makes it harder for me.

Product model:

class Product < ActiveRecord::Base    belongs_to :user          has_many :categorizations    has_many :categories, through: :categorizations      end  

Category model:

class Category < ActiveRecord::Base    belongs_to :parent, class_name: "Category"    has_many :children, class_name: "Category", foreign_key: "parent_id"    has_many :categorizations    has_many :products, through: :categorizations  end  

Categorization model:

class Categorization < ActiveRecord::Base    belongs_to :product    belongs_to :category  end  

new.html.erb

<%= simple_form_for @product, :html => { multipart: true } do |f| %>          <%= f.association :categories, collection: Category.where(parent_id: nil), prompt: 'Choose category' %>    <%= f.association :categories, collection: Category.where.not(parent_id: nil), prompt: 'Choose subcategory' %>          <%= f.button :submit, "Submit product" %>  <% end %>  

Devise token auth preventing migration

Posted: 20 Nov 2016 04:51 AM PST

My rails app is using Devise. I added devise_token_auth so I can link the app to an android app.

In the routes

namespace :api do  scope :v1 do    #mount_devise_token_auth_for 'User', at: 'auth'  end  end  

in the initializer

# enable_standard_devise_support = false #for working with Devise  

(in addition the other code that was in the file)

I got this error

:~/workspace (master) $ rake db:migrate  -- [](4.2)  -- [](4.2)  rake aborted!  NoMethodError: undefined method `[]' for #<ActiveRecord::Migration:0x00000002c3c470>  

Solution, I deleted modified the migration file

class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[4.2]  

to

class DeviseTokenAuthCreateUsers < ActiveRecord::Migration  

I stopped getting the error but now I got this

StandardError: An error has occurred, this and all later migrations canceled:    SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id" IN ........  

Please help, how can I get this to work?

Rails 5: has_many :through JSONB field association

Posted: 20 Nov 2016 04:45 AM PST

Let's assume I have has_many :through association like this:

class Model_A < ApplicationRecord    has_many :model_b, dependent: :destroy    has_many :model_c, through: :model_b    class Model_B < ApplicationRecord    belongs_to :model_a    belongs_to :model_c    class Model_C < ApplicationRecord    has_many :model_b, dependent: :destroy    has_many :model_a, through: :model_b  

My idea is to create JSONB field in Model_B and place there record IDs from records in Model_C. In addition I'd like to place in that JSONB field some other data for each record from Model_C. Considering there could be ~20 records comming from each Model_C record, so far my thinking is I could get less rows to query later on. I'm thinking here of 1m rows instead of 20m, for example.

Questions are:

  1. Would this kind of approach work and is this "Rails way"?
  2. What it would be performance wise if I have to query records in Model_B by record ID from Model_C or vice versa?

Thank you for any suggestions of how to make this the most effective way. I'm on Rails 5 and PostgreSQL 9.5.

pg_search multisearch eager loading :searchable

Posted: 20 Nov 2016 02:52 AM PST

So I'm trying to eager load the results, PgSearch.multisearch(request.headers['search']).includes(:searchable) and they aren't being included in the results. It will query the database for the models ids, but doesn't return them.

When I try to do a joins, PgSearch.multisearch(request.headers['search']).joins(:searchable)

I'm getting: ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :searchable):

All models being searched belong to :searchable. What am I missing?

Rails: how to update associated records through parent with array of ids

Posted: 20 Nov 2016 04:17 AM PST

I have an example of simple test application with has_many through association. Model Group has has_many through association with User model. Child records in the join table updated by simple @group.update(group_params) without calling associated methods. Accordingly to docs, it must looks like @group.users = (objects).

That is a question - why does it works and where is the docs. I've searched the web but find nothing.

In the groups#index view checkboxes are used to select users in the group. Params for group looks like:

"id" => "1", "group" => { "user_ids" => ["2", "4", "5"] }  

GroupsController:

def update    @group = Group.find{params[:id])    @group.update(group_params)    redirect_to groups_path  end    private  def group_params    params.require(:Group).permit(:name, user_ids:[])  end  

Models:

class User < ActiveRecord::Base    has_many :group_users    has_many :groups, through: :group_users    class Group < ActiveRecord::Base    has_many :group_users    has_many :users, through: :group_users    class GroupUser < ActiveRecord::Base    belongs_to :group    belongs_to :user  

Query postgresql json array field rails

Posted: 20 Nov 2016 04:08 AM PST

I am having a rough time trying to query a certain value in a Postgres database. I have a field named groups in the Users table that can be represented in either of these ways:

1.

groups: {"data"=>[{"serie"=>5, "year"=>3, "specialization"=>"Matematica", "management_id"=>1, "group_number"=>2}, {"serie"=>5, "year"=>3, "specialization"=>"Matematica", "management_id"=>1, "group_number"=>2}]}  

2.

groups: [{"serie"=>5, "year"=>3, "specialization"=>"Matematica", "management_id"=>1, "group_number"=>2}, {"serie"=>5, "year"=>3, "specialization"=>"Matematica", "management_id"=>1, "group_number"=>2}]  

I am fine with either of this representations. However I just can't seem to find out how to get all the users that are in serie 5 let's say. I tried multiple queries along the lines of: @users = User.where("groups ->> 'data' @> ?", {serie: 5})
@users = User.where("groups -> 'data' @> '?'", {serie: 5})
@users = User.where("groups ->> 'data' ->> 'serie' = ?", 5) And many other attempts, some more stupid than the others(as can be seen above). How would I do it?

installing rvm - connection refused

Posted: 20 Nov 2016 02:09 AM PST

I'm trying to install rvm.
I'm using the folowing guide: https://gorails.com/setup/ubuntu/16.10

When I try running, curl -sSL https://get.rvm.io | bash -s stable, I get curl: (7) Failed to connect to get.rvm.io port 443: Connection refused.
I tried opening in the browser https://get.rvm.io and I get the same error.
There is no firewall.
I tried using my cellular phone, also down.
I connected through a remote server using OpenVPN, also down.

Are there any other sources for rvm?

ActionView::Template::Error (PG::GroupingError: ERROR: column error rails

Posted: 20 Nov 2016 02:03 AM PST

When I try to use query below:

@play_lists_progress.sorted_resource.quiz_attempts.select("quiz_attempts.*,   SUM(score) as total_score").group("student_id")  

it says:

ActionView::Template::Error (PG::GroupingError: ERROR:  column   "quiz_attempts.id" must appear in the GROUP BY clause or be used in an   aggregate function  LINE 1: SELECT quiz_attempts.*, SUM(score) as total_score FROM "quiz...                 ^  : SELECT quiz_attempts.*, SUM(score) as total_score FROM "quiz_attempts" WHERE "quiz_attempts"."quiz_id" = $1 GROUP BY "quiz_attempts"."student_id"):  

What I need to do is to have results of 5 rows(currently) to a single row by grouped on student_id and the SUM of score of all these attempts.

Also @play_lists_progress.sorted_resource results:

#<Quiz id: 3, title: "java basics", time_limit_in_minutes: 4,   are_multiple_attempts_allowed: true, score_to_keep: "highest",   number_of_attempts_allowed: 10, student_see_quiz_score: "after_last_attempt",   show_one_question_at_a_time: true, is_private: false,   available_from_date_time: "2016-11-16 14:09:00", available_due_date_time:   "2016-11-16 16:45:00", instructions: "<p>XXXXXXXXXXQQQQ</p>", lesson_plan_id:   8, user_id: 3, created_at: "2016  

[Rails]Update his informations as a user

Posted: 20 Nov 2016 03:03 AM PST

I train to use rails. I have create a system of authentication for the user, of course, he can to access at this informations. But if he's connected, he can to update his informations. And now, i have a problem, the redirection with the patch work however there's no update of his informations for exemple pseudo. The user put a new pseudo, but it doesn't update. But it works in console.

code of controller sessions :

class SessionsController < ApplicationController    def new    end    def show      @page = User.find(params[:id])    end    def update      User.find(params[:id]).update name: params[:name]      redirect_to "/profil/#{current_user.id}"  end      def create      user = User.find_by_email(params[:email])      # If the user exists AND the password entered is correct.      if user && user.authenticate(params[:password])        # Save the user id inside the browser cookie. This is how we keep the user        # logged in when they navigate around our website.        session[:user_id] = user.id        redirect_to '/'      else      # If user's login doesn't work, send them back to the login form.        redirect_to '/login'      end    end      def destroy      session[:user_id] = nil      redirect_to '/login'    end  end  

code of show:

<h1>Profil</h1>     <% if current_user && @page.id == current_user.id %>  <%= form_tag "/profil/#{@page.id}", method: "patch" do %>  <ul>      <li><input type="text" name="name" value="<%= current_user.name %>" /></li>      <li><%= image_tag current_user.avatar.url(:thumb) %></li>    <input type="submit" value="Enregistrer mon profil" />  </ul>  <% end  else   %>  <%= @page.name %>  <br>  <%= image_tag @page.avatar.url(:thumb) %>     <% end %>  

code of routes :

Rails.application.routes.draw do    get 'sessions/new'      get 'users/new'      # For details on the DSL available within this file, see <a href="http://guides.rubyonrails.org/routing.html" rel="nofollow">http://guides.rubyonrails.org/routing.html</a>        get '/signup' => 'users#new'      post '/users' => 'users#create'          get '/login' => 'sessions#new'    post '/login' => 'sessions#create'    get '/logout' => 'sessions#destroy'      get '/profil/:id' => 'sessions#show'    patch '/profil/:id' => 'sessions#update'  end  

After lot of tests, I don't find my mistakes.

Sorry, if my english is no great because I'm french.

thank you in advance ^^

skipping initializer in development enviroment rails

Posted: 20 Nov 2016 01:06 AM PST

When ever, I perform a rails test in cmd line, or rails db:migrate RAILS_ENV=test I keep getting a NoMethodError for my omniauth initialzer although the rails server works fine and so does, omniauth on my, heroku site where my code is pushed to. I read this question Rails: Per-environment initializers? and added if Rails.env.production? at the top of my omniauth initialzer file so to run the omniauth initialzer only for production but I am having no luck.

The full error is;

db:migrate RAILS_ENV=test --trace  ** Invoke db:migrate (first_time)  ** Invoke environment (first_time)  ** Execute environment  rails aborted!  NoMethodError: undefined method `[]' for nil:NilClass  C:/Sites/Peoples_Profiles/config/initializers/omniauth.rb:5:in `block in <top (required)>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/omniauth-1.3.1/lib/omniauth/builder.rb:6:in `initialize'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:35:in `new'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:35:in `build'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:100:in `block in build'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:100:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:100:in `inject'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/stack.rb:100:in `build'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:508:in `block in app'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:504:in `synchronize'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:504:in `app'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:37:in `block in <module:Finisher>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `call'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'  C:/Sites/Peoples_Profiles/config/environment.rb:5:in `<top (required)>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `block in require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:328:in `require_environment!'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:448:in `block in run_tasks_blocks'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:248:in `call'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:248:in `block in execute'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:243:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:243:in `execute'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:180:in `invoke_with_call_chain'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:209:in `block in invoke_prerequisites'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:207:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:207:in `invoke_prerequisites'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:186:in `block in invoke_with_call_chain'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:180:in `invoke_with_call_chain'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/task.rb:173:in `invoke'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:152:in `invoke_task'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:108:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:108:in `block in top_level'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:117:in `run_with_threads'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:102:in `top_level'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/rake_proxy.rb:13:in `block in run_rake_task'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rake-11.3.0/lib/rake/application.rb:178:in `standard_exception_handling'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/rake_proxy.rb:10:in `run_rake_task'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:51:in `run_command!'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Tasks: TOP => db:migrate => environment  

Anyone got any ideas as to why this is?

XML generation very slow and using lots of memory in Rails 4

Posted: 19 Nov 2016 11:39 PM PST

I'm generating an XML file to share data with another system. From my troubleshooting, I've found that this process is both slow and consuming lots of memory (getting lots of R14's on Heroku.)

My index method on my Jobs Controller looks like this:

def index    respond_to do |format|      format.xml {@jobs = @user.jobs.includes(job_types: [:job_lines, :job_photos])}      format.json       {         # More code here, this part is not the problem.      }    end  end  

My view (index.xml.builder) looks like this (I've removed a bunch of fields to keep the example smaller):

xml.instruct!  xml.jobs do    @jobs.each do |j|      xml.job do        xml.id             j.id        xml.job_number     j.job_number        xml.registration   j.registration        xml.name           j.name        xml.job_types do          j.job_types.each do |t|            xml.job_type do              xml.id          t.id              xml.job_id      t.job_id              xml.type_number t.type_number              xml.description t.description              xml.job_lines do                t.job_lines.each do |l|                  xml.job_line do                    xml.id          l.id                    xml.line_number l.line_number                    xml.job_type_id l.job_type_id                    xml.line_type   l.line_type                    xml.type_number l.type_number                    xml.description l.description                    xml.part_number l.part_number                  end # job_line node                end # job_lines.each              end # job_lines node              xml.job_photos do                t.job_photos.each do |p|                  xml.job_photo do                    xml.id          p.id                    xml.pcid        p.pcid                    xml.job_type_id p.job_type_id                    xml.image_url   p.image.url                  end # job_line node                end # job_lines.each              end # job_lines node            end # job_type          end # job_types.each        end # job_types node      end # job node    end # @jobs.each  end # jobs node  

The generated XML file is not small (it's about 100kB). Running on Heroku, their Scout tool tells me that this process is often taking 4-6 seconds to run. Also, despite only running 1 worker, with 4 threads (in Puma) this part of my code is consuming all my memory. In scout, I can see that it's "Max Allocations" are as high as 10M compared with my next worst method which is only 500k allocations.

Can anyone tell me what I'm doing wrong? Is there a more efficient (in terms of speed and memory usage) way for me to generate XML?

Any help would be appreciated.

Devise Not Signing Out From ERB Link

Posted: 19 Nov 2016 11:56 PM PST

I have an app with a Devise login system for a domain and all the subdomains. It was working properly before, but now the sign out function isn't working for some reason.

I have tried this as my sign out link:

<%= link_to "Sign Out", destroy_user_session_path, :method => :delete %>  

Or, as recommended here, this as my sign out link:

<%= link_to "Sign out", logout_path, :method => :delete %>  

With this in my routes:

devise_scope :user do    delete "logout" => "devise/sessions#destroy", :as => "logout"  end  

Either way, I click the link and get something like this in my server:

Started DELETE "/logout" for 127.0.0.1 at 2016-11-19 23:09:51 -0800  Processing by Devise::SessionsController#destroy as HTML    Parameters: {"authenticity_token"=>"tbFG+joMI84Z/fu9YxCTDj+2Ltp8Wm0tC8ClirXIL4Z8+e7xuePzbn0cPyY0Ljj/UA1rxO+q3WFuO3BNHMJXTQ=="}    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]     (0.1ms)  begin transaction     (0.1ms)  commit transaction  Redirected to http://lvh.me:3000/  Completed 302 Found in 3ms (ActiveRecord: 0.2ms)      Started GET "/" for 127.0.0.1 at 2016-11-19 23:09:51 -0800  Processing by HomeController#index as HTML    Rendered home/index.html.erb within layouts/application (66.5ms)    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]  Completed 200 OK in 107ms (Views: 106.6ms | ActiveRecord: 0.1ms)  

Yet the session persists. Here's my entire routing file, if it helps:

Rails.application.routes.draw do      devise_for :users, controllers: { registrations: 'registrations' }    resources :users, only: [:show]    devise_scope :user do        delete "logout" => "devise/sessions#destroy", :as => "logout"      end        constraints subdomain: 'liz' do          scope module: 'liz', as: 'liz' do              get 'home/index'              root 'home#index'              resources :inquiries              resources :blogs              get 'tags/:tag', to: 'blogs#index', as: :tag              get 'services/hire'              get 'services/dev'              get 'services/design'              get 'services/branding'              get 'services/portfolio'          end      end        constraints subdomain: 'anthony' do          scope module: 'anthony', as: 'anthony' do              get 'home/index'              root 'home#index'          end      end        get 'home/index'      root 'home#index'      resources :logs  end  

Here are my user-related routes:

                  Prefix Verb   URI Pattern                    Controller#Action          new_user_session GET    /users/sign_in(.:format)       devise/sessions#new              user_session POST   /users/sign_in(.:format)       devise/sessions#create      destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy             user_password POST   /users/password(.:format)      devise/passwords#create         new_user_password GET    /users/password/new(.:format)  devise/passwords#new        edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit                           PATCH  /users/password(.:format)      devise/passwords#update                           PUT    /users/password(.:format)      devise/passwords#update  cancel_user_registration GET    /users/cancel(.:format)        registrations#cancel         user_registration POST   /users(.:format)               registrations#create     new_user_registration GET    /users/sign_up(.:format)       registrations#new    edit_user_registration GET    /users/edit(.:format)          registrations#edit                           PATCH  /users(.:format)               registrations#update                           PUT    /users(.:format)               registrations#update                           DELETE /users(.:format)               registrations#destroy                      user GET    /users/:id(.:format)           users#show                    logout DELETE /logout(.:format)              devise/sessions#destroy  

I don't know where else the problem could lie, but am happy to put up additional information if anyone has any ideas why this is happening.

load js file after dom changes in rails app

Posted: 19 Nov 2016 10:30 PM PST

I am using active amdin gem for building admin interface. I guess active admin uses formtastic internally for building forms.

In my form I have a Add attachment button which adds each attachments. But i want to give numbering to each attachments added. So i have implemented it as follows in a seperate file mycustomjs.js

$(document).ready(function(){    $('.has_many_add').on('click', function(){      if($(this).prev(".has_many_fields").length == 0)      {          count = 0      }      $(this).prev(".has_many_fields").prepend("<div>"+count++ +"</div>")     });           $('.has_many_remove').on('click', function(){      if($(this).parent(".has_many_fields").length)      {          count--;      }      });    });  

But the issue is that the onclick event fires before attachment element is inserted in the form. Hence on the first time click, it wont find the element with class .has_many_fields and hence wont insert the number.

On second click onwards it works fine. So is there a way to execute this script only after when the attachment dom elements are inserted??

Please find the attachment of the DOM element that is rendered.

Ruby on Rails convert date and time value properly formatted utc time

Posted: 19 Nov 2016 10:46 PM PST

I have a date value like 2016-11-19 and a time value like 2000-01-01 20:14:00 +0000

I want to convert it to proper date format which will show utc time like below: 2016-11-20 04:14:00 +0000

There lots of questions regarding this, but I am confused.

No route matches [PUT] "/articles" but I included the put route in routes

Posted: 20 Nov 2016 01:46 AM PST

Hi I'm new to rails and MVC but I'm trying really hard to learn. Right now I'm using AASM to make a transition from in_draft to published. I'm being able to make the change in rails console but when trying to use a link_to I got the error in the question

`#/app/views/welcome/dashboard.html.erb  <% if article.may_publish? %>  <%= link_to 'Publish', '/articles/#{article.id}/publish', method: :put, class: "alert-link" %>  <%end%>  

This is mi route

put '/articles/:id/publish', to: 'articles#publish'  

And my articles_controller publish method

def publish      @article.publish!      redirect_to @article  end  

On armhf/arm64 ubuntu, the ActiveRecord order method has bug?

Posted: 19 Nov 2016 08:14 PM PST

On my Nvidia jetson tx1 development board (arm64 architecture, ubuntu 16.04), when I upgrade ruby to 2.3.2, the ActiveRecord's order method is break:

bub?

In fact, after I test, This bug is present in several development boards(Nvidia Jetson TK1 and Jetson TX1, Their environment are both rails 5.0.01, ruby 2.3.2, postgresql 9.5):

2.3.0 :001 > User < ActiveRecord::Base  => true  2.3.0 :002 > User.order(:created_at)  (Object doesn't support #inspect)  =>  2.3.0 :003 > User.order(:created_at).count  NoMethodError: undefined method `blank?' for #Arel::Nodes::Ascending:0x30e1408  

For now, in order to solve this problem, I can only downgrade the ruby version to 2.3.1 (2.4.0-preview3 has the same problem), anybody can help me? thanks.

Rails turbolinks resize event and trigger

Posted: 19 Nov 2016 08:07 PM PST

Hello i'm using rails 5 and a html template. Everything works great except site menu. Mobile menu does not work properly. When i open or reload the page , my menu button does not work. But if click a link and go to another page in site , mobile menu works. I think , i can't make resize event work and also trigger. How can i change this code block to rails style :

This is from html template :

    $(window).on('load', function() {         $('#preload').addClass('completed');         $('.switch-tabs').switchTabs();      });        $(window).on('load resize', function() {         fnHeaderResize();      });       $(window).on('resize', function() {         headerFixedResize();     });       $(window).on('resize', function() {         portfolioIsotopeResize();         scrollParallax();       // Parallax         sectionCenter();        // Align Center for Section Header Responsive     }).trigger('resize');  

This is my code for rails ( but there is something missing ):

var ready;  ready = function() {      $('#preload').addClass('completed');      $('.switch-tabs').switchTabs();  };  $(document).ready(ready);  $(document).on('turbolinks:load', ready);    // after this part , i don't know how i can convert resize and trigger to rails style    $(window).on('load resize', function() {      fnHeaderResize();  });    $(window).on('resize', function() {      headerFixedResize();  });    $(window).on('resize', function() {      portfolioIsotopeResize();      sectionCenter();        // Align Center for Section Header Responsive  }).trigger('resize');  

Thank you from advance !

Rails 5 - service class to find users who have email addresses that match an organisation's domain name

Posted: 19 Nov 2016 11:40 PM PST

I am trying to learn how to use Rails 5 (generally) but specifically, I'm trying to learn how to use service classes.

I'm trying to write a service class that maps a user's given email address (user's have an attribute called :email) to organisation's domain names. Organisations have attributes called :email_format. I use that attribute to hold the part of the email address that follows the "@".

When a user creates an account, I want to take their email address that they use to sign up with, and match the bit after the @ to each of the organisations that I know about and try to find a matching one.

My attempts at this are plainly wrong, but I'm struggling to figure out why.

I have resources called User, Organisation and OrgRequest. The associations are:

User

belongs_to :organisation, optional: true  

Organisation

has_many :org_requests   has_many :users   

OrgRequest

belongs_to :user  belongs_to :organisation  

I have tried to write a service class as:

class User::OrganisationMapperService #< ActiveRecord::Base        def self.call(user: u)        new(user: user).call      end        def initialize(user: u)        self.user = user      end        def call        if matching_organisation.present?          # user.organisation_request.new(organisation_id: matching_organisation.id)          # user.update_attributes!(organisation_id: matching_organisation.id)        else          #SystemMailer.unmatched_organisation(user: user).deliver_now        end      end        private        attr_accessor :user        def matching_organisation        # User::OrganisationMapperService.new(user).matching_organisation        User::OrganisationMapperService.new(user: user)      end    end  

I then have an org requests controller with:

class Users::OrgRequestsController < ApplicationController        before_action      :authenticate_user!, except: [:new, :create, :requested]    before_action      :set_org_request, only: [:approved, :rejected, :removed]      # skip_before_action :redirect_for_unrequested_organisation    # skip_before_action :redirect_for_unknown_organisation      def index      organisation = Organisation.find_by(owner_id: current_user.id)      return redirect_to(user_path(current_user.id)) if organisation.nil?        @org_requests = organisation.org_requests    end      def new      @all_organisations    = Organisation.select(:title, :id).map { |org| [org.title, org.id] }      @org_request = OrgRequest.new#form(OrganisationRequest::Create)        matched_organisation = User::OrganisationMapperService.new(current_user).matching_organisation      @org_request.organisation_id = matched_organisation.try(:id)    end      def create      @org_request = OrgRequest.new(org_request_params)      @org_request.user_id = current_user.id        if @org_request.save        OrgRequest::ProcessService.new(org_request).process        return redirect_to(user_path(current_user),          flash[:alert] => 'Your request is being processed.')      else        # Failure scenario below        @all_organisations    = Organisation.select(:title, :id).map { |org| [org.title, org.id] }          render :new      end    end      def requested      # Need help  - if this is contained in form inputs - how do i stop from overriding the submit path?        redirect_to(user_path(current_user))      #not sure about this - a similar redirect isnt required for articles or project create    end      def approve      @org_request = current_user.organisation.org_requests.find(params[:id])        if @org_request.state_machine.transition_to!(:approved)        flash[:notice] = "You've added this member."        redirect_to org_requests_path      else        flash[:error] = "You're not able to manage this organisation's members"        redirect_to :index      end    end      def remove      @org_request = current_user.organisation.org_requests.find(params[:id])        if @org_request.state_machine.transition_to!(:removed)        flash[:notice] = "Removed from the organisation."        redirect_to action: :index        # format.html { redirect_to :index }        # format.json { render :show, status: :ok, location: @project }        # redirect_to action: :show, id: project_id        # add mailer to send message to article owner that article has been approved      else        flash[:error] = "You're not able to manage this organisation's members"        redirect_to(user_path(current_user))        # redirect_to action: :show, id: project_id      end    end      def decline      @org_request = current_user.organisation.org_requests.find(params[:id])        if @org_request.state_machine.transition_to!(:declined)        flash[:notice] = "You're not eligible to join this organisation"        redirect_to action: :index        # redirect_back(fallback_location: root_path)        # format.html { redirect_to :index }        # redirect_to action: :show, id: organisation_request.profile        # add mailer to send message to article owner that article has been approved      else        flash[:error] = "You're not able to manage this organisation's members"        redirect_to(user_path(current_user))        # redirect_to action: :show, id: organisation_request.profile      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_org_request        @org_request = OrgRequest.find(params[:id])        authorize @org_request      end        # Never trust parameters from the scary internet, only allow the white list through.      def org_request_params        params.require(:org_request).permit(:organisation_id, :name) # Need help - not sure if I need to put user id and organisation id in this permission      end    end  

I can't figure out another approach to this. When I try this, I get this error:

wrong number of arguments (given 1, expected 0)  

The error message highlights line 7 of my service class, which has:

 def initialize(user: u)        self.user = user      end  

I have previously asked questions about this problem here: superclass mismatch for class User - inheriting from ActiveRecord::Base

but I haven't managed to catch the drift of the advice or what is causing the problem. This attempt is a mash up of suggestions that I have gleaned from at least 10 different tutorials - so I appreciate that its highly unlikely to be correct, but I'm struggling to understand how the different parts of this work to know what to try differently.

Can anyone give me a steer on how to try to progress this attempt?

Rails + EasyAutoComplete "View All Results"

Posted: 19 Nov 2016 07:37 PM PST

I have a working situation going on with EasyAutoComplete, but I'd like the ability to ember a 'View All Results' button in case I type 'Forest' and want to see every set from MTG with a Forest.

View+JS

<%= form_tag("/search", method: "get") do %>    <%= label_tag(:name, "Search for:") %>    <%= text_field_tag :name, '', data: { provide: 'typeahead', source_query: autocomplete_card_name_cards_path }  %>      <!-- <#%= text_field_tag :card_name, :as => :autocomplete, :source_query => autocomplete_card_name_cards_path %> -->    <%= submit_tag("Search") %>  <% end %>      <br>    <script>    $(function(){      var options = {          url: function(phrase){            return '/cards.json?name=' + phrase          },        getValue: 'name',        list: {          match: {             enabled: true          },          maxNumberOfElements: 6,          showAnimation: {            type: "slide",            time: 300          },          hideAnimation: {            type: "slide",            time: 150          },          onChooseEvent: function(){           var multi = $("#name").getSelectedItemData().multi;           var code = $("#name").getSelectedItemData().code;           window.location.href = '/cards/' + code;          }        },        theme: "round",        template: {          type: "custom",          method: function(value, item) {            return "<img src='"+item.image+"' class='autoImage'/> " + value + "<br>"+ item.text;           }        }      };        $("#name").easyAutocomplete(options);    })  </script>  

Controller

  def index      @cards = Card.order(:name).limit(10)      @cards.where!("name like '%#{params[:name]}%'") if params[:name]    end  

JSON Builder

json.array!(@cards) do |card|    json.code card.id    json.name "#{card.name} | #{card.cardtype} | #{card.setName}"    json.image card.image_url    json.text card.text  end  

Currently it just pulls data from the /cards endpoint. I can probably see how to append another element to the list of 6 it makes with a link going to that JSON Page, but then I'd need to make another View that can render the JSON properly.

I'm wondering if anyone knows of a helper function for this script, or an easier way to go about doing this?

Currently I think I'll just make a page that it redirects too, and passed the end-point and renders it.

AKA I click View All I get sent to /search, and the endpoint /cards?name=For comes with it, and I render the top ~10 results from that. This doesn't feel very DRY at all though and I imagine there is a simpler way?

Clarification on Ruby syntax in Rails

Posted: 19 Nov 2016 07:27 PM PST

I'm learning Rails and in going through the official guides, I came across some code which I could not really understand the meaning of.

Case 1 -

class Person < ApplicationRecord    validates :name, presence: true  end   

It looks to me that validates is a method that takes a symbol called :name as an argument. But then, what is presence? Is it also a method? But if it is, what is the significance of the : right after presence. I understand that the value true is being set for presence, which serves as kind of a validation, requiring the presence of (in other words). But I'm not quite clear on the syntax.

It might also be possible that presence: true is just a hash, where :presence (the symbol) is the key, and true is the value.

Case 2 -

class Person < ApplicationRecord    validates :terms_of_service, acceptance: true, message: 'must be abided'  end   

Again, validates is the method that takes a symbol :terms_of_service as an argument. But what about the rest? Is it a hash with 2 key-value pairs, somewhat like {acceptance: true, message: 'must be abided'}?

And if it is indeed a hash, why is it tacked on to the validates method in each case? Why can't it be

validates :terms_of_service  acceptance: true, message: 'must be abided'  

Thanks for the help!

How to get group by with all columns ruby on rails

Posted: 20 Nov 2016 07:20 AM PST

I have belongs to and has many relationship between Quiz and Quiz Attempts.

Quiz has many Quiz Attempts.

What I need is to show all Quiz Attempts based on student_id with sum of scores of that student.

The code I am trying and giving results is:

@play_lists_progress.sorted_resource   

returns Quiz hash below and based on that quiz hash I want to loop quiz attempts with grouping of sum of score and students with other columns

    #<Quiz id: 3, title: "java basics", time_limit_in_minutes: 4,   are_multiple_attempts_allowed: true, score_to_keep: "highest",   number_of_attempts_allowed: 10, student_see_quiz_score: "after_last_attempt",   show_one_question_at_a_time: true, is_private: false,   available_from_date_time: "2016-11-16 14:09:00", available_due_date_time:   "2016-11-16 16:45:00", instructions: "<p>XXXXXXXXXXQQQQ</p>", lesson_plan_id:   8, user_id: 3, publish_date: "2016-11-10 20:27:32", created_at: "2016-11-10   20:27:31", updated_at: "2016-11-16 11:17:08", is_publish: false, subject_id:   3, teacher_id: 1, popularity_count: 0, show_answers: "after_the_quiz">  

Complete query: @play_lists_progress.sorted_resource.quiz_attempts.group(["student_id"]).sum(: score)

which returns query:

(0.3ms)  SELECT SUM("quiz_attempts"."score") AS sum_score, student_id AS   student_id FROM "quiz_attempts" WHERE "quiz_attempts"."quiz_id" = $1 GROUP   BY "quiz_attempts"."student_id"  [["quiz_id", 3]]  

The above query works and show only 2 column {1=>26.6}, student id and score and it makes records as array which I do not like to have.

Here is columns in quiz attempts table:

quiz_id  student_id  score  

jQuery not multiplying numbers correctly

Posted: 19 Nov 2016 05:34 PM PST

Im trying to use some jQuery functions to multiply the values of two number_field's in rails.

My jQuery code is this:

$('#mycometer_coc_sample_bv1').change(function() {    $('#cv').empty();    var BV1 = $('#mycometer_coc_sample_bv1').val();    var BV2 = $('#mycometer_coc_sample_bv2').val();    $('#mycometer_coc_sample_cv').val( ( BV2 - BV1 )*0.84 + BV2 );    $('#cv').append( $('#mycometer_coc_sample_cv').val() );  });    $('#mycometer_coc_sample_bv2').change(function() {    $('#cv').empty();    var BV1 = $('#mycometer_coc_sample_bv1').val();    var BV2 = $('#mycometer_coc_sample_bv2').val();    $('#mycometer_coc_sample_cv').val( ( BV2 - BV1 )*0.84 + BV2 );    $('#cv').append( $('#mycometer_coc_sample_cv').val() );  });  

#mycometer_coc_sample_cv is a hidden number_field used to send the value back to my controller. Im displaying that value into a div of #cv

The first function works correctly. The examples numbers I've been using are BV1 = 2, BV2 = 12. When entering 2 into BV1 I get the correct output into CV of -1.68, But when entering the second value 12 into BV2 I get 8.412, when the correct output should be 20.4

I have no idea whats going wrong. Can anyone help debug this?

Some screenshots: Entering first value = correct output enter image description here

Second value something goes wrong and incorrect output. CV should equal 20.4

(12-2) = 10 => 10*0.84 = 8.4 => 8.4 + 12 = 20.4 enter image description here

Rails 4.2.7 mysql set two custom primary key

Posted: 19 Nov 2016 05:59 PM PST

I have two tables called Post and Like. I want to set "ip" and "reference to post" as my two primary key in Like table. I can successfully create the likes table with two unique key 'ip' and 'id' from posts table. But when I try to create sample data from my rails console it will first check if the same 'ip' exist. If the same 'ip' is already existing it will not create the data even if the post is completely a different one.

This is what I have so far.

Likes Table

class CreateLikes < ActiveRecord::Migration   def change   create_table :likes, :id => false do |t|     t.string :ip, limit: 39     t.references :post, index: true, foreign_key: true       t.timestamps null: false   end   add_index :likes, ["ip"], :unique => true      add_index :posts, ["id"], :unique => true   end   

end

Posts Table

class CreatePosts < ActiveRecord::Migration   def change   create_table :posts do |t|     t.string :title     t.string :body     t.string :media       t.timestamps null: false   end     end  end  

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete