Saturday, October 8, 2016

Proper handling of Category model in Rails | Fixed issues

Proper handling of Category model in Rails | Fixed issues


Proper handling of Category model in Rails

Posted: 08 Oct 2016 07:45 AM PDT

My application has Category and App model that i want to associate

Category => has_many :apps , App => belong_to :category

I what user to be able to select category when creating and updating app model and it was successful done tutorial i use.

The problem is when user create the app model forgetting to pass any category the application crashed (I dont know how to handle this )

The application crash with error

Again, when user create the app model passing the category then decided to edit it later . . the category field wont point to the last selected category( showing the prompt "select category"), the same error happen when user opt not update the category field!

My form partial

<%= simple_form_for @app do |f| %>    <%= select_tag(:category_id, options_for_select(@categories), {:prompt => "--select category--"}) %>    <%= f.input :title, label: "Application title" %>    <%= f.input :creator %>    <%= f.input :description %>    <%= f.button :submit %>  <% end %>  

My apps_controller

def new      @app = current_user.apps.build      @categories = Category.all.map { |c| [c.name, c.id]  }  end    def create      @app = current_user.apps.build(app_params)      @app.category_id = params[:category_id]        if @app.save          redirect_to root_path      else          render :new      end  end    def edit      @categories = Category.all.map { |c| [c.name, c.id]  }    end    def update      @app.category_id = params[:category_id]      if @app.update(app_params)          redirect_to @app      else          render :edit      end  end  

What am I doing wrong? How can I accurately handle this situation?

database "db/development.sqlite3" does not exist - how to fix?

Posted: 08 Oct 2016 07:23 AM PDT

a friend deployed my application on Heroku, and it works fine there. But I can not open my application on local server. Can anyone help?

When going on localhost i get the following error message:

ActiveRecord::NoDatabaseError FATAL: database "db/development.sqlite3" does not exist

Extracted source (around line #661):

    rescue ::PG::Error => error        if error.message.include?("does not exist")          raise ActiveRecord::NoDatabaseError.new(error.message, error)        else          raise        end  

Changing Spree from_address

Posted: 08 Oct 2016 07:05 AM PDT

I am trying to change Spree 3.0 from_email

I added this line to my spree initialiser, but it does not work:

Spree::Store.current.mail_from_address = "x@x.com"  

Do you know of any reason why not?

I also put it directly in my mailer decorator:

Spree::OrderMailer.class_eval do    def confirm_email_to_store(order, resend = false)      Spree::Store.current.mail_from_address = "x@x.com"      @order = order.respond_to?(:id) ? order : Spree::Order.find(order)      subject = (resend ? "[#{Spree.t(:resend).upcase}] " : '')      subject += "#{'Will Call' if @order.will_call} #{'Just to See' if @order.just_to_see} ##{@order.number}"      mail(to: ENV['STORE_EMAIL'], from: from_address, subject: subject)    end  end  

This also did not work

ActiveRecord::RecordNotFound in PermitsController#detail, Couldn't find Permit with 'id'=

Posted: 08 Oct 2016 07:28 AM PDT

Hi guys I keep get this error when i try to access to render out one specific permit data from the permits model to the detail.html.erb, i search through all my code and couldn't find the bug. Can you guys help me to check which part i did wrong? Btw I'm implementing a website using Ruby on rails

This is my permits_controller.rb

class PermitsController < ApplicationController    before_action :set_permit, only: [:destroy]    def index      @permits = Permit.where(:user_id => current_user.id)    end      def new      @permits = Permit.new    end      def create      @permits = current_user.permits.build(permit_params)      if @permits.save        redirect_to invoice_path      else        render 'new'      end    end        def destroy      Permit.destroy_all(user_id: current_user)      respond_to do |format|        format.html { redirect_to root_path, notice: 'Permit was successfully canceled.' }        format.json { head :no_content }      end    end      def confirm      @fields = %i[vehicle_type, carplate, studentid, name, department, permitstart, permitend]      @permit = current_user.permits.build(permit_params)      render :new and return unless @permit.valid?    end          def show      @permits = Permit.where(:user_id => current_user.id)    end      def update      @permits = Permit.where(user_id: current_user).take      respond_to do |format|        if @permits.update(permit_params)          format.html { redirect_to root_path}          flash[:success] = "Permit successfully updated"          format.json { render :show, status: :ok, location: @user }        else          format.html { render :edit }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end      def edit      @permits = Permit.find(params[:id])      #@permits = Permit.find_or_initialize_by(user_id: params[:id])    end    def detail      @permits = Permit.find(params[:id])    end      private    # Use callbacks to share common setup or constraints between actions.    def set_permit      @permits = Permit.find(params[:id])    end      # Never trust parameters from the scary internet, only allow the white list through.    def permit_params      params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration, :permitstart, :permitend)    end  end  

Detail.html.erb

<% provide(:title, 'New Permit') %>  <h1>Permit Application</h1>    <div class="row">    <div class="col-md-6 col-md-offset-3">              <h2><%= @permits.permitstart %></h2>      </div>  </div>  

Route.db

Rails.application.routes.draw do    resources :users    resources :permits do      collection do        post :confirm      end    end    resources :visitor_permits    root 'static_pages#home'      get 'viewpermit' =>'permits#detail'      get 'invoice' => 'permits#invoice'    get 'payment' =>'transaction#new'    get 'show_visitor_permit' =>'visitor_permits#show'    get 'show_permit' =>'permits#show'    get 'visitorpermit' => 'visitor_permits#new'    post 'createpermit' => 'permits#create'    get 'homepage/index'    post 'permits' => 'permits#create'    get 'permitapplication' => 'permits#new'    get 'adminlogin' => 'admin_controller#index'    get 'patrollogin' => 'patrol_officer_controller#index'    get 'createcitation' => 'citations#new'    get 'contact'=> 'static_pages#contact'    get 'about' => 'static_pages#about'    get 'signup' => 'users#new'    get 'help' => 'static_pages#help'    post 'users' => 'users#create'    get 'login' => 'sessions#new' #Page for a new session    post 'login' => 'sessions#create' #Create a new session    delete 'logout'=>'sessions#destroy' #Delete a session        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  end  

This is my linking page (show.html.erb)

<h2>My Permits</h2>  <table>    <tr>      <th>Permit Start Date</th>      <th>Permit End Data</th>      <th>Action</th>      <th> </th>    </tr>  <% @permits.each do |permit| %>      <tr>      <td><%= permit.permitstart %></td>      <td><%= permit.permitend %></td>      <td><%= link_to 'Detail', viewpermit_path(permit) %></td>      <td><%= link_to 'Edit', edit_permit_path(permit) %></td>    </tr>    <% end %>    </table>  

Proper way of using sass with Rails

Posted: 08 Oct 2016 06:37 AM PDT

At first, I have written all css styles in one file but things get complicated so I have divided my sass files to folders. I found an article from internet and I followed it. It says "if we put _ in front of sass file, it will not indexed by compiler"

  • Created 3 folders
  • Created files _test_name.scss like that
  • Created _index.scss file for every folder and import all other scss files in that folder
  • Created main.scss file and import all index.scss files in it.

Everything is working fine but if I use color variable in somewhere in other folder it didn't wok. It gave me undefined variable error message. After that I imported colors scss file then it worked. But that's strange right? It should work without importing colors scss file. Now the thing is if I see my styles in developer tools, the same style repeating three times! Please check image

enter image description here

Am I did something wrong here?

rails datepicker saving todays date instead

Posted: 08 Oct 2016 07:20 AM PDT

Hi i am having trouble with saving the date using datepicker , it saves todays date instead and not the one i entered. My start_time has date and time.

this is my form

 <%= f.label :start_time, 'start date and time' %>      <%= f.text_field :start_time, "data-provide" => 'datepicker' %>    <%= f.time_select :start_time, :ampm => true, :minute_step => 30, class: 'form-control' %>      <script type="text/javascript">    $(document).ready(function(){    $('.datepicker').datepicker({    format: "dd-mm-yyyy"  });    });  </script>  

I have tried changing the date formats but it is not helping. Thank you

How can I stub in setup method with Minitest?

Posted: 08 Oct 2016 06:09 AM PDT

How can I use stub method in setup? I only found the stub with block like this:

class FooTest < ActiveSupport::TestCase    test 'for_something' do      Foo.stub :some_method, 3 do        #assert_equal      end    end    end  

But I want to stub for all tests. How can I stub it?

Ruby on Rails checking object before instantiate it

Posted: 08 Oct 2016 05:11 AM PDT

i have two models X and Y x has many y y belongs to x at y controller i need to add a method that constrain the ability of x to see or edit any other y but its related one lets say i created an object x1 that connected 3 different y and x2 that connected to 4 other different y at show page if i call any y by id ill get it regardless session[x.id] is i need to compare x.id with y.x_id if they are equal return true the problem that i need to do that before instantiate the y object i dont want to use any gems if any one can help ill deeply appreciate it. thank you

Rails AJAX remote: true with dynamic id

Posted: 08 Oct 2016 05:30 AM PDT

I implemented a basic AJAX Call in Rails, which is working fine with this:

index.html.erb

<a href="/days/new" data-remote="true" id="new_day_ajax">Add This day</a>  

new.js.erb

$('#new_day_ajax').hide().after('<%= j render("form")%>');  

The problem is I generate up to 31 a-tags like the above one on a single page with the following loop and the form will of course always show up at the first one, no matter which link I click:

end_date.downto(start_date).each do |date|      [...]  

To make the form show up at the clicked link I tried to generate the ids dynamically like so:

id="new_day_ajax_<%= date.strftime('%d') %>" <!-- i.e. new_day_ajax_07 -->  

but now I don't know how to pass this dynamic id into the new.js.erb. How can I know the dynamic id inside of the javascript?

Thanks in advance!

Rails create join table object should not create but update in special case

Posted: 08 Oct 2016 04:41 AM PDT

In a webshop I have a booking that needs to know if a booking already exists in the order. I had the whole thing working, but then the details...

...now 'booking on a product' (or in normal English: Adding a product to your shopping-cart) adds a totally new booking on the order list in each case. It oughtn't when this product is already booked once, then it only should alter the quantity.

So easy right? Just one simple if-statement and the whole thing works.

  def create      @order = current_order      # If product has already been booked      if @order.bookings.where(product_id: params[:product_id]).exists?        # Then: Only alter the quantity in the booking.        @booking = @order.bookings.where(product_id: params[:product_id])        @booking.product_quantity = params[:product_quantity]      else        # Else: Make a new booking.        @booking = @order.bookings.new(booking_params)        @product = @booking.product        @booking.product_name = @product.name        @booking.product_price = @product.price      end      @order.sum_all_bookings       @order.save    end      # ...      def booking_params      params.require(:booking).permit(:product_quantity, :product_id)    end  

Doesn't seem to work.

How do I make the check in the if-statement? Or should I go about a whole different route to update the booking?

Which version of Ruby Docker image should I use?

Posted: 08 Oct 2016 02:35 AM PDT

As helpful as this is

https://hub.docker.com/_/ruby/

I'm looking for a clear cut answer and thought process in deciding which version of the ruby Docker image I should use for my application.

Regards,

Does ActiveRecord object not have instance variables for it's attributes but only methods?

Posted: 08 Oct 2016 04:46 AM PDT

In Rails I have the following model:

class Recipe < ActiveRecord::Base      attr_accessible :name , :description ,           :t_baking , :t_cooling , :t_cooking ,:t_rest        # other stuff here    end  

with t_baking , t_cooling , t_cooking ,t_rest as Time.

So In my view I want to loop on each value.

<% ['cooking', 'baking', 'cooling' , 'rest'].each do |time| %>      <% time_of_recipe = @recipe.instance_variable_get("@t_#{time}") %>      <% if time_of_recipe.is_a? Time %>          <%= time_of_recipe.strftime "%H:%M"  %>      <% else %>          <%= time_of_recipe %>      <% end %>  <% end %>  

It doesn't work because

@recipe.instance_variable_get("@t_cooking").class # give NilClass  

but

@recipe.t_cooking.class # give Time  

Why?

How to sort by weighted rating

Posted: 08 Oct 2016 02:07 AM PDT

I'm using the ratyrate gem for adding ratings on shows and I'm trying to sort them with a weighted rating:

Model def:

def ranking      a = RatingCache.find_by(:cacheable_type => 'Show')      r = a.avg      v = a.qty      m = 1      c = RatingCache.where(:cacheable_type => 'Show').average(:qty)      (v / (v+m)) * r + (m / (v+m)) * c  end  

Controller:
@sranking = RatingCache.where(:cacheable_type => Show').sort_by(&:ranking)

View:

<% @sranking.each do |s| %>    <%= s.cacheable_id %>  <% end %>  

However this just outputs the cacheable_id's in numerical order. How can I properly sort shows by a weighted rating?

How do online shops send a percentage to their bank accounts, while other part is sent to a seller?

Posted: 08 Oct 2016 03:42 AM PDT

I am interested in creating an online shop for the company that takes 5% of the cost of whatever item is selling, and then transfer it to company's bank account.

For example: A-customer, B-seller, C-online shop.

A buys a cap that costs $20 so that B gets $19(95%) and C gets $1(5%).

A process should execute automatically. How to manage these operations and What technology should I use? Writing in Ruby on Rails.

I am new to e-commerce, and if you provide an advice, I will be happy, thank you!

Rails : How to accessing relation attributes from the view

Posted: 08 Oct 2016 05:25 AM PDT

I have the following rails code

Employee model: id | emp_name | emp_number

class Employee < ActiveRecord::Base        has_many :visitors  end  

Visitor Model:id|employee_id|visitor_name|vis_company|vis|email

    class Visitor < ActiveRecord::Base      belongs_to :employee  end  

Employee Controller :

class EmployeesController < ApplicationController    before_action :set_employee, only: [:show, :edit, :update, :destroy]      # GET /employees    # GET /employees.json    def index      @employees = Employee.all    end      # GET /employees/1    # GET /employees/1.json    def show    end      # GET /employees/new    def new      @employee = Employee.new    end      # GET /employees/1/edit    def edit    end      # POST /employees    # POST /employees.json    def create      @employee = Employee.new(employee_params)        respond_to do |format|        if @employee.save          format.html { redirect_to @employee, notice: 'Employee was successfully created.' }          format.json { render :show, status: :created, location: @employee }        else          format.html { render :new }          format.json { render json: @employee.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /employees/1    # PATCH/PUT /employees/1.json    def update      respond_to do |format|        if @employee.update(employee_params)          format.html { redirect_to @employee, notice: 'Employee was successfully updated.' }          format.json { render :show, status: :ok, location: @employee }        else          format.html { render :edit }          format.json { render json: @employee.errors, status: :unprocessable_entity }        end      end    end      # DELETE /employees/1    # DELETE /employees/1.json    def destroy      @employee.destroy      respond_to do |format|        format.html { redirect_to employees_url, notice: 'Employee was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_employee        @employee = Employee.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def employee_params        params.require(:employee).permit(:emp_id, :emp_name, :emp_email, :emp_phone, :emp_mobile)      end  end  

Visitor Controller :

class VisitorsController < ApplicationController    before_action :set_visitor, only: [:show, :edit, :update, :destroy]      # GET /visitors    # GET /visitors.json    def index      #@visitors = Visitor.find(:all, :order => 'emp_name')      #@visitors = Visitor.all.includes(:emp_name)      @visitors = Visitor.all      #@employees = @visitors.Employee.find(:all, :order => 'emp_name')          #@employees = @visitors.employee :include => [:emp_name]    end      # GET /visitors/1    # GET /visitors/1.json    def show    end      # GET /visitors/new    def new      @visitor = Visitor.new    end      # GET /visitors/1/edit    def edit    end      # POST /visitors    # POST /visitors.json    def create      @visitor = Visitor.new(visitor_params)        respond_to do |format|        if @visitor.save          format.html { redirect_to @visitor, notice: 'Visitor was successfully created.' }          format.json { render :show, status: :created, location: @visitor }        else          format.html { render :new }          format.json { render json: @visitor.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /visitors/1    # PATCH/PUT /visitors/1.json    def update      respond_to do |format|        if @visitor.update(visitor_params)          format.html { redirect_to @visitor, notice: 'Visitor was successfully updated.' }          format.json { render :show, status: :ok, location: @visitor }        else          format.html { render :edit }          format.json { render json: @visitor.errors, status: :unprocessable_entity }        end      end    end      # DELETE /visitors/1    # DELETE /visitors/1.json    def destroy      @visitor.destroy      respond_to do |format|        format.html { redirect_to visitors_url, notice: 'Visitor was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_visitor        @visitor = Visitor.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def visitor_params        params.require(:visitor).permit(:vis_id, :vis_name, :vis_email, :vis_company, :employee_id)      end  end  

Now my main problem is that I cant access employee name from visitor view :

<p id="notice"><%= notice %></p>    <h1>Listing Visitors</h1>    <table>    <thead>      <tr>        <th>Vis</th>        <th>Vis name</th>        <th>Vis email</th>        <th>Vis company</th>        <th>Visitor Host</th>        <th colspan="3"></th>      </tr>    </thead>      <tbody>      <% @visitors.each do |visitor| %>        <tr>          <td><%= visitor.id %></td>          <td><%= visitor.vis_name %></td>          <td><%= visitor.vis_email %></td>          <td><%= visitor.vis_company %></td>          <td><%= visitor.employee.emp_name %></td>          <td><%= link_to 'Show', visitor %></td>          <td><%= link_to 'Edit', edit_visitor_path(visitor) %></td>          <td><%= link_to 'Destroy', visitor, method: :delete, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>    </tbody>  </table>    <br>    <%= link_to 'New Visitor', new_visitor_path %>  

ActiveRecord::RecordNotFound in PermitsController#show, Couldn't find Permit with 'id'=

Posted: 08 Oct 2016 01:20 AM PDT

Hi guys I keep get this error when i try to access to SHOW action(Manage permit button on user/show.html.erb) which should display all the permits of a specific user, i search through all my code and couldn't find the bug. Can you guys help me to check which part i did wrong? Btw I'm implementing a website using Ruby on rails

This is my permits_controller.rb

class PermitsController < ApplicationController    before_action :set_permit, only: [:show, :destroy]    def index      @permits = Permit.where(:user_id => current_user.id)    end      def new      @permits = Permit.new    end      def create      @permits = current_user.permits.build(permit_params)      if @permits.save        redirect_to invoice_path      else        render 'new'      end    end        def destroy      Permit.destroy_all(user_id: current_user)      respond_to do |format|        format.html { redirect_to root_path, notice: 'Permit was successfully canceled.' }        format.json { head :no_content }      end    end      def confirm      @fields = %i[vehicle_type, carplate, studentid, name, department, permitstart, permitend]      @permit = current_user.permits.build(permit_params)      render :new and return unless @permit.valid?    end          def show      @permits = Permit.where(:user_id => current_user.id)        end      def update      @permits = Permit.where(user_id: current_user).take      respond_to do |format|        if @permits.update(permit_params)          format.html { redirect_to root_path}          flash[:success] = "Permit successfully updated"          format.json { render :show, status: :ok, location: @user }        else          format.html { render :edit }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end      def edit      @permits = Permit.find(params[:id])      #@permits = Permit.find_or_initialize_by(user_id: params[:id])    end      private    # Use callbacks to share common setup or constraints between actions.    def set_permit      @permits = Permit.find(params[:id])    end      # Never trust parameters from the scary internet, only allow the white list through.    def permit_params      params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration, :permitstart, :permitend)    end  end  

This is my permits/show.html.erb

<%= @permits.name %>  

This is my route.db

Rails.application.routes.draw do    resources :users    resources :permits do      collection do        post :confirm      end    end    resources :visitor_permits    root 'static_pages#home'    get 'invoice' => 'permits#invoice'    get 'payment' =>'transaction#new'    get 'show_visitor_permit' =>'visitor_permits#show'    get 'show_permit' =>'permits#show'    get 'visitorpermit' => 'visitor_permits#new'    post 'createpermit' => 'permits#create'    get 'homepage/index'    post 'permits' => 'permits#create'    get 'permitapplication' => 'permits#new'    get 'adminlogin' => 'admin_controller#index'    get 'patrollogin' => 'patrol_officer_controller#index'    get 'createcitation' => 'citations#new'    get 'contact'=> 'static_pages#contact'    get 'about' => 'static_pages#about'    get 'signup' => 'users#new'    get 'help' => 'static_pages#help'    post 'users' => 'users#create'    get 'login' => 'sessions#new' #Page for a new session    post 'login' => 'sessions#create' #Create a new session    delete 'logout'=>'sessions#destroy' #Delete a session        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  end  

users/show.html.erb

<!DOCTYPE html>  <html>  <body>    <div id="sidebar">  <ul id="mySidenav" class="sidenav">    <li><%= link_to "New Parking Permit", permitapplication_path %></li>    <li><%= link_to "Manage Permit", show_permit_path(@permit) %></li>    <li><%= link_to "New Visitor Parking Permit", visitorpermit_path %></li>    <li><%= link_to "Manage Visitor Permit", "#" %></li>    <li><%= link_to "Check Fines", "#" %></li>    <li><%= link_to "New Health and Safety Report", "#" %></li>    <li><%= link_to "Manage Health and Safety Report", "#" %></li>  </ul>  </div>      </body>  </html>  

config.static_cache_control isn't setting cache-control in rails 4

Posted: 07 Oct 2016 11:47 PM PDT

I have a rails 4 application and I'm trying to set cache-control to true so images, css and js are cached by the browser. Everything I have read says to add the following to the production.rb file.

config.serve_static_files = true  config.static_cache_control = "public, max-age=2592000"  

But it doesn't do anything. Cache-control is still set to cache-control: max-age=0, private, must-revalidate. I cant find anything more that needs to be done for this to work.

Additive scope conditions for has_many :through

Posted: 08 Oct 2016 04:27 AM PDT

I want a user to be able to find all posts that have one or more tags. And I'd like the tags to be additive criteria, so for example you could search for posts that have just the 'News' tag, or you could search for posts that have both the 'News' and 'Science' tags.

Currently what I have, and it works, is a Post model, a Tag model, and a join model called Marking. Post has_many :tags, through: :markings. I get what I need by passing an array of Tag ids to a Post class method:

post.rb

def self.from_tag_id_array array    post_array = []    Marking.where(tag_id: array).group_by(&:post_id).each do |p_id,m_array|      post_array << p_id if m_array.map(&:tag_id).sort & array.sort == array.sort    end    where id: post_array  end  

This seems like a clunky way to get there. Is there a way I can do this with a scope on an association or something of the like?

Rails 5.0 - cucumber-rails gem

Posted: 08 Oct 2016 12:55 AM PDT

I am having trouble trying to install cucumber-rails gem on rails 5.0 . It throws the following error: Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://rubygems.org/gems/addressable-2.4.0.gem) An error occurred while installing addressable (2.4.0), and Bundler cannot continue. Make sure that gem install addressable -v '2.4.0' succeeds before bundling.

gem install addresssable then throws a gem not found error. Any help is appreciated.

Is there any possible way to calculate estimated delivery date of USPS mail service in rails?

Posted: 07 Oct 2016 10:15 PM PDT

I want to calculate estimated delivery date of USPS mail service. Active Shipping provide estimated rate but not estimated delivery date. Is there any other option for calculate USPS estimated delivery date?

Setting up Foreign Keys in Rails with Postgres

Posted: 08 Oct 2016 12:16 AM PDT

I am attempting to track mutual likes where a user likes a user that likes them. To check if the like is mutual, I call an method after the like is created. If that liker has been a likee than it is considered mutual.

The problem however, is that I run into some odd errors that I believe are related to how the foreign keys have been set up. I have set up a has many association in Rails but any time I attempt to access it, I get a PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block : RELEASE SAVEPOINT active_record_1 error.

User:

class User < ApplicationRecord    has_many :likes  end  

Like:

class Like < ApplicationRecord    belongs_to :likee, class_name: 'User', foreign_key: 'likee_id'    belongs_to :liker, class_name: 'User', foreign_key: 'liker_id'    belongs_to :connection, optional: true      after_save :mutual_like?      private      def mutual_like?        if liker.likes.where(likee: liker)        # fails      end    end  end  

I've tried changing the hook to be around save, etc. but that doesn't work either.

Also, I cannot even call Like.first else I get the same error.

I've tried printing out liker.likes.where(likee: liker) and i get PG::UndefinedColumn: ERROR: column likes.user_id does not exist which I think is the problem.

I can however, access the liker like this: self.likee inside of the hook but I cannot call self.likee.likes without it returning #<Like::ActiveRecord_Associations_CollectionProxy:0x3fd91ca5ca78>

Schema:

  create_table "likes", force: :cascade do |t|      t.integer  "liker_id",      null: false      t.integer  "likee_id",      null: false      t.integer  "connection_id"      t.datetime "created_at",    null: false      t.datetime "updated_at",    null: false      t.index ["likee_id"], name: "index_likes_on_likee_id", using: :btree      t.index ["liker_id"], name: "index_likes_on_liker_id", using: :btree    end            create_table "users", force: :cascade do |t|      t.string   "email"      t.string   "username"      t.string   "password_digest"      t.boolean  "admin",                default: false      t.index ["email"], name: "index_users_on_email", using: :btree      t.index ["username"], name: "index_users_on_username", using: :btree    end  

Tests:

RSpec.describe Like, type: :model do    let(:liker) { Fabricate(:user) }    let(:likee) { Fabricate(:user) }    let(:like) { Fabricate(:like, liker: liker, likee: likee) }    let(:pending_like) { Fabricate.build(:like, liker: liker, likee: likee)}      context 'relations' do      it { should belong_to :likee }      it { should belong_to :liker }        describe 'liking another user' do          it '#liker references first user' do          expect(like.likee).to eq likee        end          it '#likee references second user' do          expect(like.liker).to eq liker        end        end    end    ...    RSpec.describe User, type: :model do    context 'relations' do      it { should have_many :likes }    end   ...  

Is this caused because I'm attempting to lookup a record that is being saved?

Actionmailer images sending in development not staging or production

Posted: 07 Oct 2016 09:05 PM PDT

So I'm having an issue where images sent from the development server are getting displayed in emails, but when sent in production/staging mode the images aren't displayed in the email, however when copying the image url from the email source I can display the image in the browser. I have another app that's running with virtually the same production.rb file and it's sending the image without issue, so I'm not sure what I'm missing.

development.rb

Rails.application.configure do      config.cache_classes = false    config.eager_load = false    config.consider_all_requests_local       = true    config.action_controller.perform_caching = false      config.action_mailer.raise_delivery_errors = true    config.action_mailer.perform_deliveries = true      host = 'development.local'    config.action_mailer.default_url_options = { host: host, protocol: 'https' }    config.action_mailer.delivery_method = :smtp    config.action_mailer.asset_host = 'https://development.local'    config.action_mailer.smtp_settings = {      address:              "smtp.gmail.com",      port:                 587,      domain:               "gmail.com",      user_name:            ENV["GMAIL_USER"],      password:             ENV["GMAIL_PASS"],      authentication:       :plain,      enable_starttls_auto: true    }      config.active_support.deprecation = :log    config.active_record.migration_error = :page_load    config.assets.debug = true    config.assets.digest = true    config.assets.raise_runtime_errors = true    config.web_console.whitelisted_ips = '172.17.0.0/16'    config.web_console.whitelisted_ips = '0.0.0.0/0.0.0.0'  end  

staging.rb/production.rb

Rails.application.configure do    config.cache_classes = true    config.eager_load = true    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true      config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?    config.assets.js_compressor = :uglifier    config.assets.compile = false    config.assets.digest = true    config.force_ssl = true      config.log_level = :debug      config.action_controller.asset_host = 'https://production.local'      config.action_mailer.raise_delivery_errors = true    config.action_mailer.perform_deliveries = true    host = "production.local"    config.action_mailer.asset_host = 'https://production.local'    config.action_mailer.default_url_options = { host: host, protocol: 'https' }    config.action_mailer.delivery_method = :smtp    config.action_mailer.smtp_settings = {      :address              => "smtp.gmail.com",      :port                 => 587,      :domain               => "gmail.com",      :user_name            => ENV["GMAIL_USER"],      :password             => ENV["GMAIL_PASS"],      :authentication       => :plain,      :enable_starttls_auto => true      }      config.i18n.fallbacks = true    config.active_support.deprecation = :notify    config.log_formatter = ::Logger::Formatter.new    config.active_record.dump_schema_after_migration = false  end  

views/user_mailer/account_activation.html.erb

<div style="overflow:hidden;max-width:600px;margin:auto;border-radius:7px;box-sizing:border-box;box-shadow:0 6px 12px rgba(0, 0, 0, 0.175);">    <div style="overflow:hidden;background:#a1cbd6;color:#603914;padding:10px 20px;box-sizing: border-box;">      <%= image_tag('logo_h.png', style: "float:left;") %> <h1 style="float:left;margin:15px 15px 5px;">Test Company</h1>    </div>      <div style="overflow:hidden;background:#fff;padding:25px;box-sizing: border-box;">      <p>Hi <%= @user.name %>,</p>        <p>This account allows you to access everything you need</p>        <p>Activate your account by clicking the link below:</p>        <%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email) %>      </div>  </div>  

How can I set browser caching on just .png files in rails 4

Posted: 07 Oct 2016 08:25 PM PDT

Most of the content on my side isn't static but the images are (and there are a lot of images). I want to enable browser caching on .png files to make googles page speed test happier. Looking into it I see I can use something like config.static_cache_control = "public, max-age=2419200" in the production.rb file. But this caches everything including html. I just want .png files cached.

In htaccess files you just add the following to cache just .png files

`<filesMatch ".(png)$">  Header set Cache-Control "max-age=2419200, public"  </filesMatch>`  

But for rails I'm not sure what to do.

Rails changing colour of bootstrap list item using link_to

Posted: 08 Oct 2016 05:30 AM PDT

I'm trying to change the colour of a bootstrap list item based on whether the correct answer to a question is selected...but using link_to is making it complicated. Advice appreciated. Thx.

    <ul class="list-group" id="answered">        <% @question.answers.each do |answer| %>      <%= link_to(answer.text, question_path(@question, attempted_answer: answer.id), :class => "list-group-item") %>           <% if @attempted_answer && @attempted_answer == answer %>           <% if @attempted_answer.correct %>              correct              <% else %>                incorrect              <% end %>            <% end %>  

Change redmine routes

Posted: 07 Oct 2016 07:53 PM PDT

www.redmine.org

We use Redmine for asset tracking and I would like to update the URLs. Presently the URLs revolve around issues and does not look right for assets.

I would like to update it so that I would navigate to:

www.domain.com/assets instead of www.domain.com/issues

Using: Route alias in Rails

I have looked at routes.rb and changed the line:

resources :issues do  

to

resources :issues, :path => :assets do  

Unfortunately it doesn't work...

learn link_to on Ruby on Rails

Posted: 07 Oct 2016 10:40 PM PDT

this code:

<%= link_to 'Show', home %></td>  <%= link_to 'New Post', new_home_path %>  

that code above make by default scaffold, if i add code like this:

<%= link_to 'About', about %></td>  

->:

<%= link_to 'Show', home %></td>     <%= link_to 'About', about %></td>      <%= link_to 'New Post', new_home_path %>  

then run/refresh show error,why error? i know that error is add code <%= link_to 'About', about %></td> but I see in homesController nothing see home and new_home_path? and in routers.rb same.

Uploaded video can only display on my website

Posted: 08 Oct 2016 06:25 AM PDT

I wish to upload video to some video websites (need to be viewable in China, therefore EXCLUDE Youtube.com) and have it displayed only on my website. User cannot use the link to display it directly or embed it on their website. Is such function available for any video uploading website, and how should I achieve this purpose?

having problems with the login link using Spree

Posted: 07 Oct 2016 05:58 PM PDT

So I tried to add the login link on my Spree Rails app by following the documentation in http://guides.spreecommerce.org/developer/authentication.html However I haven't been able to get the link on my app.enter image description here

I created app/overrides/auth_login_bar.rb file following the documentation adding the following code to the file.

Deface::Override.new(:virtual_path => "spree/shared/_nav_bar",    :name => "auth_shared_login_bar",    :insert_before => "li#search-bar",    :partial => "spree/shared/login_bar",    :disabled => false,    :original => 'eb3fa668cd98b6a1c75c36420ef1b238a1fc55ad')

I also updated config/routes.rb file:

Rails.application.routes.draw do      # This line mounts Spree's routes at the root of your application.    # This means, any requests to URLs such as /products, will go to Spree::ProductsController.    # If you would like to change where this engine is mounted, simply change the :at option to something different.    #    # We ask that you don't use the :as option here, as Spree relies on it being the default of "spree"    mount Spree::Core::Engine, at: '/'                    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html            devise_scope :person do          get '/login', :to => "devise/sessions#new"          get '/signup', :to => "devise/registrations#new"          delete '/logout', :to => "devise/sessions#destroy"          end    end

I don't seem to find how to fix it.

Rails 5 - getting started with React.js

Posted: 07 Oct 2016 06:33 PM PDT

I'm trying to learn how to use react.js in my Rails 5 app.

I have installed react-rails gem.

I have used the generator to create my first component as follows:

rails generate react:component AppRole title:string display_name:string category:integer --es6  

That gave me a file in app/javascripts/components called app_role.es6.jsx which has:

class AppRole extends React.Component {    render () {      return (        <div>          <div>Title: {this.props.title}</div>          <div>Display Name: {this.props.displayName}</div>          <div>Category: {this.props.category}</div>        </div>      );    }  }    AppRole.propTypes = {    title: React.PropTypes.string,    displayName: React.PropTypes.string,    category: React.PropTypes.node  };  

I watched this egghead.io getting started video (as well as having purchased Arkency's react with rails book and read this tutorial .

I didn't use the air pair tutorial because I'm trying to learn es6. I got stuck using the Arkency books because there are no complete examples and I got lost in the gaps where the book assumes knowledge.

However, even the getting started video from Egghead isn't working for me. I follow their structure, and try to render the index page, which has:

<p><%= react_component('App_Role', title: 'hello') %></p>  

A blank white page renders. When I inspect it, I can see:

<div data-react-class="App_Role" data-react-props="{&quot;title&quot;:&quot;hello&quot;}"></div>  

When I use the chrome add-on for react, I can see the react that olark messaging plugin uses but nothing else. The egghead tutorial at least renders the 'hello' text.

When I use the chrome inspector to look at the console tab, I get an error that says app role is not defined:

VM4231:1 Uncaught ReferenceError: App_Role is not defined(anonymous function) @ VM4231:1getConstructor @ react_ujs_mount.self-5293119….js?body=1:58mountComponents @ react_ujs_mount.self-5293119….js?body=1:77(anonymous function) @ react_ujs_turbolinks.self-19cb50a….js?body=1:5dispatch @ jquery.self-bd7ddd3….js?body=1:5227elemData.handle @ jquery.self-bd7ddd3….js?body=1:4879t.dispatch @ turbolinks.self-c5acd7a….js?body=1:6t.Controller.r.notifyApplicationAfterPageLoad @ turbolinks.self-c5acd7a….js?body=1:6t.Controller.r.pageLoaded @ turbolinks.self-c5acd7a….js?body=1:6(anonymous function) @ turbolinks.self-c5acd7a….js?body=1:6  

Can anyone see what I've done wrong?

Input hidden with array value - Ruby on Rails

Posted: 07 Oct 2016 07:02 PM PDT

I'm trying to send an array for use in javascript from html with a Ruby's variable like this:

 <% @data.each do |d| %>     <input type="hidden" id="name" value= "<%= d.name %>">   <% end %>  

"data" is a variable of a model

def index      @data = organizations.all  end  

in js i used a variable with id "name"

var nombre = document.getElementById("name").value;  var x = name;  

I want that x is an array like:

["Org1","Org2","Org3"]  

thanks for everything

No comments:

Post a Comment