lundi 8 janvier 2018

Rails 5 - How to sort has_many associations list?

In rails 5 and in postgresql, I want to sort a list based on created_at: :desc.

Model structure is like,

Review model has_many :comments and has_many :commented_users, :through=>:comments

In views, I want to display list of users based on created_at (DESC) date and this field is from comments table

Controller query is like,

review = Review.find_by_id(params[:id])
comments = review.commented_users

If I give order for review.commented_users then obviously it will sort User, how can I sort users based on Comment?

Please help me to solve this sorting issue and I am new to postgresql

dimanche 7 janvier 2018

Ruby on Rails ActiveRecord::PendingMigrationError

When I try to load my rails app on my local host I get an error telling me to resolve it by running rails db:migrate but when I try to run the command this is what I get

C:\Sites\CoolGuyGear>rails db:migrate == 20180108004216 AddDeviseToViews: migrating ================================= -- change_table(:views) rails aborted! StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email: ALTER TABLE "views" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in'

Caused by: ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "views" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in'

Caused by: SQLite3::SQLException: duplicate column name: email C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in' Tasks: TOP => db:migrate (See full trace by running task with --trace)

ID param not being sent to Controller when manually changing routes

I have looked through the other answers provided on StackOverflow, and none of them answered my question. Here is what is happening with my code.

Error

undefined method `update' for nil:NilClass

Problem: It looks like the param id is not being sent to the controller from the form as they show up as nil in the console using byebug.

console readout:

(byebug) params[:id]
nil
(byebug) @support
nil
(byebug) params[:title]
nil
(byebug) params[:support]
<ActionController::Parameters {"title"=>"Test", "subtitle"=>"testing", 
"website"=>"www.test.com", "type_of_support"=>"", "description"=>""}
permitted: false>
(byebug) params[:support][:id]
nil
(byebug) params[:support][:title]
"Test"

I do not believe that the problem is with the form as it is the same form partial used for the new/create action and the params are sent to the controller then and the object is created (though in that case there is no id, since it is generated when creating the object, not passed from the form).

You can see in my code below that the route for PATCH is just 'support' without the :id param. If I try to add that to the route, I get an error stating that there is no route matching 'support/'. So, I have to take away the :id param in the route for it to pass the information to the controller.

I am at a loss here. How do I pass the :id to the controller? How does rails do this? Before I manually change the routes, the automatic routes from resources :supports includes an :id param for the PATCH route and it works. What am I doing wrong that it won't allow me to add that to the route?

Code:

config/routes.rb

get    'support',          as: 'supports',     to: 'supports#index'
post   'support',                              to: 'supports#create'
get    'support/new',      as: 'new_support',  to: 'supports#new'
get    'support/:id/edit', as: 'edit_support', to: 'supports#edit'
get    'support/:title',   as: 'support_page', to: 'supports#show'
patch  'support/',                             to: 'supports#update'
put    'support/:id',                          to: 'supports#update'
delete 'supports/:id',                         to: 'supports#destroy'

Results this for rake routes:

supports     GET    /support(.:format)                supports#index
support      POST   /support(.:format)                supports#create
new_support  GET    /support/new(.:format)            supports#new
edit_support GET    /support/:id/edit(.:format)       supports#edit
support_page GET    /support/:title(.:format)         supports#show
             PATCH  /support(.:format)                supports#update
             PUT    /support/:id(.:format)            supports#update
             DELETE /supports/:id(.:format)           supports#destroy

app/controllers/supports_controllers.rb

class SupportsController < ApplicationController
  before_action :set_support_by_title, only: [:show]
  before_action :set_support_by_id,    only: [:edit, :update, :destroy]

  def index
    @supports = Support.all
  end

  def show
  end

  def new
    @support = Support.new
  end

  def edit
  end

  def create
    @support = Support.new(support_params)

    respond_to do |format|
      if @support.save
        format.html { redirect_to @support, 
                      notice: 'Support was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    # byebug
    respond_to do |format|
      if @support.update(support_params)
        format.html { redirect_to @support, 
                      notice: 'Support was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @support.destroy
    respond_to do |format|
      format.html { redirect_to supports_url, 
                    notice: 'Support was successfully destroyed.' }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_support_by_title
      @support = Support.find_by(title: params[:title])
      # byebug
    end

    def set_support_by_id
      @support = Support.find(params[:id])
      # byebug
    end

    # Never trust parameters from the scary internet, 
    # only allow the white list through.

    def support_params
      params.require(:support).permit(:title, 
                                      :subtitle, 
                                      :website, 
                                      :type_of_support, 
                                      :description)
    end
end

app/views/supports/edit.html.erb

<h1>Editing Support</h1>

<%= render 'form', support: @support %>

<%= link_to 'Show', support_page_path(@support.title) %> |
<%= link_to 'Back', supports_path %>

app/views/supports/_form.html.erb

<%= form_with(model: support, local: true) do |form| %>
  <% if support.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(support.errors.count, "error") %> 
          prohibited this support from being saved:
      </h2>

      <ul>
      <% support.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    Title: 
    <%= form.text_field :title, id: :support_title %>
  </div>

  <div class="field">
    Subtitle: 
    <%= form.text_field :subtitle, id: :support_subtitle %>
  </div>

  <div class="field">
    Website: 
    <%= form.text_field :website, id: :support_website %>
  </div>

  <div class="field">
    Type of Support: 
    <%= form.text_field :type_of_support, id: :support_type %>
  </div>

  <div class="field">
    Description: 
    <%= form.text_area :description, id: :support_description %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

samedi 6 janvier 2018

Trying to find a good way to chain scopes dynamically

I found this article on cleaning up chained scopes that would be great in a project I'm working on. However, some of my scopes have arguments. I can't think of a way to make this work with arguments. I tried string interpolation which I suspected wouldn't work and of course, didn't.

http://ift.tt/2ddyejQ

def self.send_chain(methods)
  methods.inject(self, :send)
end

$ methods = ["with_author", "pending_review", "draft", "flagged", "published", "with_website", "with_meta_title", "with_meta_description"]
$ Article.send_chain(methods)

How I can make admin, users, dashboard, and other settings

I need to develop admin dashboard for my further projects. I am junior and won't become a super ruby developer. can anyone help me or show me links.

Select expired and not expired values MySQL, Rails 5

I have Ruby on Rails 5 with MySQL app. I have table products and table subscription with the standard Rails 5 datetime column - created_at'.

The model Product has_many :subscriptions and the model Subscription belongs_to :product.

I want to select all subscriptions for a product that are created before for the example 1 day and all products that are created (for the example last 24 hours) in this way that I can use them like this - product.expired_subscriptions and product.active_subscriptions.

vendredi 5 janvier 2018

Fake URL for a page using rails

I am new to rails and I was wondering if it is possible to have a fake URL for a page that is there is a different package. For example if I have my main website running on xyz.com and on clicking a button it takes me to xyz-abc.com/page but I want the address in the url bar to show as xyz.com/page Can you please help me figure this out.