Friday, October 14, 2016

Database not recognizing dynamically generated instances of model in form using Cocoon | Fixed issues

Database not recognizing dynamically generated instances of model in form using Cocoon | Fixed issues


Database not recognizing dynamically generated instances of model in form using Cocoon

Posted: 14 Oct 2016 07:42 AM PDT

I've almost finished a form using cocoon that manages deeply nested forms that need to dynamically generate parts of the form. The database is set up as Visualizations has_many Rows, Rows has_many panes.

Now, I have this completely working. But when I add my styling in, it breaks the form entirely, I've since stripped down quite a bit of the styling to try and find the issue, but it still is persisting. I know that the issue lies within my cover_image form subset as everything relating to rows and panes has not been touched with styling yet.

//Cover Image Upload Preview & Delete  $(function() {    function readURL(input) {      if (input.files && input.files[0]) {        var reader = new FileReader();          reader.onload = function (e) {          $('#img_preview').attr('src', e.target.result);        }        reader.readAsDataURL(input.files[0]);      }    }      $("#visualization_cover_image").change(function(){      $('#img_preview').removeClass('hidden');      readURL(this);    });  });    //Displays cover image preview after file has been selected from desktop  $(function(){    $('input#visualization_cover_image').click(function() {      $('.img_prev').css({"display":"block"})      $('#trash-can_cover').css({"display":"none"})    });  });    //Displays Title box for input  $(function(){    $('label#text_preview').click(function() {      $('.inputtext').css({"display":"inline-block"});      $('label#text_preview').hide();    });  });
//image_form.scss    label:hover {    color: black;    text-decoration: underline;  }    .inputfile {  	width: 0.1px;  	height: 0.1px;  	opacity: 0;  	overflow: hidden;  	position: absolute;  	z-index: -1;  }    .inputfile + label {      margin-top: 3.5em;      font-size: 1.2em;      color: white;      display: inline-block;      padding-left: 10%;  }    .inputfile:focus + label,  .inputfile + label:hover {      color: black;      text-decoration: underline;  }    .pre_img_prev {   width: 1200px;   height: 170px;   position: relative;   overflow: hidden;   background-color: #ADADAD;   color: #ecf0f1;  }    .gray_bar {    float: left;    width: 1.7em;    height: 100em;    background-color: #828282;  }    .img_prev {    display: none;    position: relative;  }    #img_preview {   left: 0;   top: 0;   width: 100em;   height: 100em;   position: absolute;   }    #text_preview {  margin-top: 2.3em;  font-size: 1.2em;  color: white;  display: inline-block;  position: relative;  }      .inputtext {    display: none;    background: transparent;    top: 4.2em;    right: 25em;    width: 200px;    color: white;    position: relative;  }  .inputtext:focus {    background: transparent;  }      .inputtext + label {    padding-top: 24px;    color: white;    display: inline;    }
<div class="try">    <div class="breadcrumb-wrapper">      <ul class="breadcrumbs">          <li>            placeholder          </li>        </ul>        <%= form_for @visualization, :html => {:multipart => true} do |f| %>      </div>      <div class="cover_image text-center">        <div class="row pre_img_prev">          <div class="gray_bar"></div>          <div class="field img_prev">            <img id="img_preview" src="#" alt="your image" class="img-thumbnail hidden text-center"/>            <%= f.label :title, "+ Add Title", id: "text_preview"%>            <%= f.text_field :title, name: "visualization[title]", id: "visualization[title]", class: "inputtext"%>            <div class="trash-can_title">              <a href="#" id="trash-can_title"><i class="fa fa-trash fa-3x" aria-hidden="true"></i></a>            </div>          </div>          <div class="field">            <%= f.label :cover_image, "+ Add Cover Image" %>            <%= f.file_field :cover_image, class: "inputfile" %>            <%= f.hidden_field :cover_image_cache %>          </div>          <div class="trash-can_cover">            <a href="#" id="trash-can_cover"><i class="fa fa-trash fa-3x" aria-hidden="true"></i></a>          </div>        </div>      </div>      <div id="rows" class="row">        <%= f.fields_for :rows do |row| %>        <%= render 'row_fields', :f => row %>        <% end %>        <div class="links">          <%= link_to_add_association "Add Row", f, :rows %>        </div>      </div>      <div class="actions">        <%= f.submit %>      </div>

If anyone could help me spot the issue I would very much appreciate it as I have narrowed it down to here but have been staring at this for a few hours now and haven't got a clue why it isn't working.

Ruby on Rails - Check where assets (.js) is loaded

Posted: 14 Oct 2016 07:35 AM PDT

Im building a application where I give my clients a .js file so they can include into <head></head> and that .js file is providing some functions to my clients website.

Basically the .js file is the path to show.js.erb view. I am looking for protecting my code and looking for a way so clients/users can't just load the http://localhost:3000/js_files/2.js path on their browser and see the code.

Every client has different ID (.js path) and different website and I can detect that from my db. Is there a way so I see if the file/path is loading from my clients website and if Yes load/show the js code, otherwise not showing anything.

In other words, a way to check if file is loaded on for ex: mydomain.com or if they just copy the path into their browser.

I have read about obfuscate, but its not useful in my case.

Save a Time object in JSONB

Posted: 14 Oct 2016 07:17 AM PDT

I have a JSONB field in my database defined like this:

t.jsonb  :some_data, null: false, default: []  

I've tried to save time objects to this field by any of the below methods

my_instance.some_data = [Time.now]  my_instance.some_data = Time.now  

But upon save the time objects gets converted to strings and the following format "2016-10-15T06:00:00.000Z".

Why does this conversion occur and is it possible to save time objects?

Show nested_fields rails 4

Posted: 14 Oct 2016 07:15 AM PDT

i have a weird problem with "nested_form" in rails. I made a model "evaluate" associated to other model "proyect", but when i try to show theres fields, on "proyects" form, just show fields from "proyects".

Here is my code:

Models:

proyect.erb

class Proyect < ActiveRecord::Base  belongs_to :user  has_many :vercions #I know is versions  has_many :evaluates #I know is evaluators  accepts_nested_attributes_for :evaluates, allow_destroy: true  validates :titulo,:presence => true,                      :length => { :minimum => 3 }  validates :descripcion,:presence => true,                      :length => { :minimum => 3 }      end  

evaluate.erb

class Evaluate < ActiveRecord::Base    belongs_to :proyect    has_and_belongs_to_many :users  end  

Controller proyects_controller.erb

class ProyectsController < ApplicationController    before_action :set_proyect, only: [:show, :edit, :update, :destroy]      # GET /proyects    # GET /proyects.json    def index          if current_user.tipo == 'i'              @proyects = Proyect.where(:user_id => current_user.id)              else          @proyects = #Proyect.where(:id_user => current_user.id)                Proyect.all        end    end          # GET /proyects/1    # GET /proyects/1.json    def show      @vercion = Vercion.new    end      # GET /proyects/new    def new      @proyect = Proyect.new      @proyect.evaluates.build    end      # GET /proyects/1/edit    def edit      end      # POST /proyects    # POST /proyects.json    def create      @proyect = current_user.proyects.new(proyect_params)        respond_to do |format|        if @proyect.save          format.html { redirect_to @proyect, notice: 'Proyecto creado!.' }          format.json { render :show, status: :created, location: @proyect }        else          format.html { render :new }          format.json { render json: @proyect.errors, status: :unprocessable_entity }        end        # Llamamos al   ActionMailer que creamos          Usermailer.bienvenido_email(current_user,@proyect).deliver      end    end      # PATCH/PUT /proyects/1    # PATCH/PUT /proyects/1.json    def update      respond_to do |format|        if @proyect.update(proyect_params)          format.html { redirect_to @proyect, notice: 'Proyect was successfully updated.' }          format.json { render :show, status: :ok, location: @proyect }          else          format.html { render :edit }          format.json { render json: @proyect.errors, status: :unprocessable_entity }        end      end    end      # DELETE /proyects/1    # DELETE /proyects/1.json    def destroy      @proyect.destroy      respond_to do |format|        format.html { redirect_to proyects_url, notice: 'Proyect was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_proyect        @proyect = Proyect.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def proyect_params        params.require(:proyect).permit(          :titulo, :descripcion,:evaluador, :id_user, :codigo, :user_assign,evaluates_attributes: [:id,:nombre, :prioridad, :_destroy,  user_ids: []  ])      end  end  

Views _form.html.erb(Proyects)

<%= nested_form_for(@proyect) do |f| %>    <% if @proyect.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@proyect.errors.count, "error") %> prohibited this proyect from being saved:</h2>          <ul>        <% @proyect.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>      <div class="field">      <%= f.label :titulo %><br>      <%= f.text_field :titulo %>    </div>    <div class="field">      <%= f.label :descripcion %><br>      <%= f.text_area :descripcion %>    </div>    <div class="field">      <%= f.hidden_field :id_user, :value => current_user.id %>     </div>    <!--Aqui aƱadi algo-->    <fieldset id="evaluates">      <%= f.fields_for :evaluates do |evaluates_form| %>        <div class="field">                <%= evaluates_form.label :status %><br>          <%= evaluates_form.text_field :status %>        </div>        <%= evaluates_form.link_to_remove "Eliminar esta tarea" %>      <% end %>      <p><%= f.link_to_add "Agregar una tarea", :evaluates %></p>    </fieldset>   <div class="actions">      <%= f.submit %>    </div>  <% end %>  

_evaluate_fields.html.erb

<div class="field">    <%= f.label :status, 'Nombre de la tarea' %><br>    <%= f.text_field :status %>  </div>  <div class="field">    <%= f.collection_check_boxes :user_ids, User.where(:tipo => 'e'), :id, :cedula %>  </div>  <%= f.link_to_remove "Eliminar Evaluador" %>  

If someone know, how to solve it, i'll be grateful.

God bless you

How do I upgrade from Rails 4.2.7.1 to Rails 5.0.0.1?

Posted: 14 Oct 2016 07:14 AM PDT

I'm using 4.2.7.1 and I want to upgrade to Rails 5.0.0.1. So I adjusted my Gemfile like so

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '~> 5.0.0.1'  # Use Puma as the app server  gem 'puma', '~> 3.0'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.2'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks  gem 'turbolinks', '~> 5'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.5'  # Use Redis adapter to run Action Cable in production  # gem 'redis', '~> 3.0'    gem 'uuids'  gem 'addressable'  gem 'postgresql'  gem 'pundit'  gem 'omniauth-oauth2', '~> 1.3.1'  gem 'omniauth-google-oauth2'  gem 'omniauth-facebook'  gem 'omniauth-twitter'  gem 'omniauth-linkedin-oauth2'  gem 'jquery-ui-rails'  gem 'will_paginate'  gem 'bootstrap-sass'  gem 'autoprefixer-rails'  gem 'compass-rails'  gem 'pdf-reader'  gem 'jquery-turbolinks'  gem 'tor', :git => 'https://github.com/dryruby/tor.rb.git'  gem 'tor_requests'  gem 'tor-privoxy'  gem 'net-telnet'  gem 'mechanize'  gem 'activerecord-import'  

but when I try and run "bundle install" (after deleting Gemfile.lock), I get these errors …

localhost:myproject davea$ bundle install  Fetching https://github.com/dryruby/tor.rb.git  Fetching gem metadata from https://rubygems.org/.........  Fetching version metadata from https://rubygems.org/...  Fetching dependency metadata from https://rubygems.org/..  Resolving dependencies.................................................  Bundler could not find compatible versions for gem "activerecord":    In Gemfile:      activerecord-import was resolved to 0.16.1, which depends on        activerecord (>= 3.2)        rails (~> 5.0.0.1) was resolved to 5.0.0.1, which depends on        activerecord (= 5.0.0.1)        uuids was resolved to 1.4.0, which depends on        activerecord (~> 4.1)  Bundler could not find compatible versions for gem "hexx-active_record":    In Gemfile:      uuids was resolved to 4.0.0, which depends on        hexx-active_record (~> 1.3)    Could not find gem 'hexx-active_record (~> 1.3)', which is required by gem 'uuids', in any of the sources.Bundler could not find compatible versions for gem "rails":    In Gemfile:      rails (~> 5.0.0.1)        uuids was resolved to 0.0.1, which depends on        rails (~> 4.1)  

What do I need to do to get my Rails version upgraded?

Tiny_TDS Error displays Invalid Object

Posted: 14 Oct 2016 07:10 AM PDT

I'm working on a rails api and and am getting:

TinyTds::Error: Invalid object name 'users_campaigns'.: EXEC sp_executesql N'SELECT [users_campaigns].* FROM [users_campaigns] WHERE [users_campaigns].[campaign_id] = 8 AND [users_campaigns].[is_active] = 1' (ActiveRecord::StatementInvalid)  

The name of the table 'users_campaigns' matches the database table, the database connection is correct, and I have explicitly defined the table name in the model to avoid pluralization issues:

class UserCampaign < ActiveRecord::Base      self.table_name = 'users_campaigns'    end  

I'm running tiny_tds 1.0.5, activerecord-sqlserver-adapter 4.1.0, Rails 4.1.0, SQL Server 2008.

How to keep gemset on changing tab in mac terminal? [duplicate]

Posted: 14 Oct 2016 07:01 AM PDT

This question already has an answer here:

I am trying to keep the gemset of rvm when I create a new terminal tab on Mac OS. I know that I can set a gemset as a default but I don't want to do this.

Maybe someone can help me with this question.

Thanks a lot.

Requests get stuck in PG::Connection#async_exec when running under passenger

Posted: 14 Oct 2016 06:39 AM PDT

I'm trying to make a rails application work under passenger with no luck so far. It uses sequel to connect to postgresql. Requests randomly take too much time to complete. I was able to find where the app is spending its time:

 %self      total      self      wait     child     calls  name   99.92     65.713    65.713     0.000     0.000        5   PG::Connection#async_exec    0.00      0.002     0.002     0.000     0.000      264   Set#delete  ...  

Supposedly, it doesn't happen with webrick, and I'm going to try and run it under unicorn.

Here are some related links.

I'm using passenger-5.0.30, ruby-2.3.0, postgresql-9.4, pg-0.19.0, rails-5.0.0.1.

undefined local variable or method `object'

Posted: 14 Oct 2016 07:37 AM PDT

In my Rails 5 app, I have this error:

undefined local variable or method `object'

when I use this table to list the tags of a related object (in this case an Annotation)

<tbody>          <% object.tags.each do |tag| %>              <% unless tag.content.blank? %>              <tr>                  <td style="word-wrap: break-word;" class="displaytagedit"><%= link_to tag.content, [object, tag], method: :patch %></td>  

It calls this form:

<%= simple_form_for @tag, html: { class: 'form-vertical', multipart: true },      wrapper: :horizontal_form,      wrapper_mappings: {      check_boxes: :horizontal_radio_and_checkboxes,      radio_buttons: :horizontal_radio_and_checkboxes,      file: :horizontal_file_input,      boolean: :horizontal_boolean      } do |f| %>      <%= f.error_notification %>      <%= f.input :content, placeholder: 'Tagged content', label: false %>      <%= f.association :tagtype, prompt: 'Select tag type', label: false, :collection => Tagtype.active.order(:name).where(:documenttype => object.documenttype_id) %>      <%= f.input :location, :as => :hidden, :input_html => { :value => 'x=0, y=0' }, label: false %>      <%= f.button :submit %>  <% end -%>  

Tags are a reusable model on (for now) 2 objects.

This is the routes.rb

Rails.application.routes.draw do    root 'dashboard#index'    devise_for :users    resources :users, :documenttypes, :tagtypes, :business_partners      resources :documents do      resources :comments, :tags      get "pdf", on: :member       end      resources :annotations do      resources :comments, :tags      get "pdf", on: :member    end  

Update

this is the tag controller:

class TagsController < ApplicationController    def create      tagable = detect_tagable      tagable.tags.create(tag_params)      redirect_to tagable_path(tagable)  end    def update     tagable = detect_tagable     @tag = tagable.tags.find(params[:id])     @tags = Tag.all     render '_tag_update'  end    def destroy     tagable = detect_tagable     @tag = tagable.tags.find(params[:id])     @tag.destroy     redirect_to tagable_path(tagable)  end      private        def tagable_path(tagable)        case tagable        when Document          document_path(tagable)        when Annotation          annotate_path(tagable)        else          fail 'Unknown tagable'        end      end        def detect_tagable        if params[:annotation_id]          Annotation.find(params[:annotation_id])        elsif params[:document_id]          Document.find(params[:document_id])        else          fail 'Tagable not found'        end      end        def tag_params        params.require(:tag).permit(:content, :location, :tagtype_id, annotation_attributes: { annotation_ids:[] }, document_attributes: { document_ids:[] })      end    end  

where is my error/mistake?

Pass devise current_user to a method in a lib file

Posted: 14 Oct 2016 06:31 AM PDT

I am trying to pass the devise @current_user from my application_controller to a class method in a library file. This is to use the Twitter API. I can get it working by writing the various twitter methods in the application_controller file, but I was wondering how I would do it using a separate lib. file and class instead? The code is as follows:

lib/twitter_api.rb

class TwitterApi    def self.our_public_tweets    client.user_timeline('BBCNews', count: 1, exclude_replies: true, include_rts: false)  end    def self.followers    client.followers.take(5)  end    def self.client    @client ||= Twitter::REST::Client.new do |config|     config.consumer_key        = Rails.application.secrets.twitter_api_key     config.consumer_secret     = Rails.application.secrets.twitter_api_secret     config.access_token        = current_user.token     config.access_token_secret = current_user.secret      end    end  end  

application_controller.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception      def current_user      @current_user ||= User.find(session[:user_id]) if session[:user_id]    end  end  

view file: index.html.erb

  <%= TwitterApi.our_public_tweets.each do |tweet| %>      <%= tweet.text %>    <% end %>      <%= TwitterApi.followers.each do |follower| %>      <%= follower.name %>    <% end %>  

Show image after changing format in Rails using imagemagic

Posted: 14 Oct 2016 06:47 AM PDT

I want to show images, I've got urls to do that, but I've got one problem - all of them have extensions 'ico' and I want them to be converted to 'png' and then shown in the view. Is there any simple way to do that or I have to format and save them into model and then show?

How to implement autocomplete search from google in rails ?

Posted: 14 Oct 2016 06:08 AM PDT

I am newbie in rails ,i don't know how implement this feature in application . please suggest me any basic idea.

if any user create a book ->

1) Book name should be auto suggested like Google search(if user enter a name , it should be automatically search correct name from Google and suggest to user ).

2) Author name also be auto suggested like Google Search(if user enter a name , it should be automatically search correct name from Google and suggest to user ).

Book Model has following attributes .

> Book.new    =>Book(id: integer, user_id: integer, author: string, name: string, published_at: datetime)  

stuck in an edit method with rails

Posted: 14 Oct 2016 05:37 AM PDT

I'm stuck in an easy edit method and can't go on until I solve it.

I have a list of items in the index view, each item has a view item button, a delete button, and an edit button.

I have no problem with create, show and delete, but I'm stuck with te edit method.

this is my activities_controller.rb

def edit      @activity = Activity.find(params[:id])      if @activity.update(activity_params)          redirect_to @activity      else          redirect_to :edit      end  end    private        def activity_params          params.require(:activity).permit(:name, :description)      end  

and this is the edit view:

<%= form_for(@activity) do |f| %>      <p>          <%= f.text_field :name %>          <%= f.label :name, "Name" %>      </p>      <p>          <%= f.text_area :description" %>          <%= f.label :description, "Descripction" %>      </p>  <p>      <%= f.submit "save", class: "btn" %>  </p>  

In the list of items view:

<% @activities.each do |activity| %>      <%= activity.name %>      <%= link_to "edit", edit_activity_path(activity), class: "btn"%>  <% end %>  

In all the examples I followed they do the edit button in the show item view, so they use @activity as a path param, but in my loop I can't use @activity and I use activity. I think here is my noob fail but I can't figure how to fix it.

So when I enter to for example localhost:3000/activities/11/edit it shows me the message "param is missing or the value is empty: activity".

As I said before I think it is because I am passing as a path param activity instead of @activity and then it has not the structure I did for the strong param "activity_params". But at this moment I don't see the solution.

Wrong version of dependence gem when run test for my gem

Posted: 14 Oct 2016 05:19 AM PDT

I have been developing gem. For test my gem I use ActiveRecord. When I run test I get some error because my gem doesn't support version 5.0 of ActiveRecord.

But in my gemspec I have:

spec.add_development_dependency 'activerecord', '~> 4.2'  

Also I tried to user Gemfile.local but it didn't get positive result.

What a right way for set particular version for a gem?

How to set on delete cascade in database migration? [Cakephp 3]

Posted: 14 Oct 2016 05:16 AM PDT

can we set on delete cascade while creating a table using migrations in Cakephp. I did the same thing in Rails project, for example:

Rails Example:

create_table :profiles do |t|      t.references :user, index: true, unique: true, foreign_key: {on_delete: :cascade}  end  

but now i want to use the same thing in cakephp, i have tried a lot but nothing helped.

Note: i am using phinx plugin as database migration.

Thanks.

Rails 5: Remote form failing

Posted: 14 Oct 2016 07:12 AM PDT

I have a form for create products in my rails app:

= form_for product, url: url, method: :post, html: { class: 'product-form' }, remote: true do |f|      .row      .col-xs-12.col-sm-6        .form-group.required          = f.label :name          = f.text_field :name, autofocus: true, class: 'form-control'      .col-xs-12.col-sm-6        .form-group.required          = f.label :price          .input-group            .input-group-addon $            = f.number_field :price, class: 'form-control'      .row      .col-xs-12        .form-group          = f.label :description          = f.text_area :description, class: 'form-control'      .row      .col-xs-12        .form-group          = label_tag :images, 'Images'          = f.file_field :images, multiple: true, class: 'form-control'      .row      .col-xs-12.text-right        = f.submit "Cancel", class: 'btn btn-default', data: { dismiss: "modal" }        = f.submit "Save",  class: 'btn btn-primary'  

It works fine on my development environment. But when running on heroku (production), it fails when clicking on "Save" (note that I am using Devise and the login/signup works fine), with this error:

2016-10-14T11:55:02.825234+00:00 app[web.1]: W, [2016-10-14T11:55:02.825168 #3] WARN -- Can't verify CSRF token authenticity.

2016-10-14T11:55:02.825602+00:00 app[web.1]: I, [2016-10-14T11:55:02.825555 #3] INFO -- : Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

2016-10-14T11:55:02.826511+00:00 app[web.1]: F, [2016-10-14T11:55:02.826471 #3] FATAL -- : ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

The thing is when I don't select an image, it works fine. So I think the problem might be with the image uploader:

models/product.rb

class Product    mount_uploaders :images, ProductImageUploader    # more stuff...  end  

uploaders/product_image_uploader.rb

class ProductImageUploader < CarrierWave::Uploader::Base    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end  end  

initializers/carrier_wave.rb

if Rails.env.development? || Rails.env.test?    CarrierWave.configure do |config|      config.storage = :file      config.enable_processing = false if Rails.env.test?    end  else    CarrierWave.configure do |config|      config.fog_provider = 'fog/aws'                        # required      config.fog_credentials = {        provider:              'AWS',        aws_access_key_id:     ENV["AWS_KEY_ID"],        aws_secret_access_key: ENV["AWS_KEY_SECRET"],        region:                'us-west-2',                  # optional, defaults to 'us-east-1'      }        config.fog_directory = ENV['AWS_BUCKET']      config.fog_public = true        config.cache_dir = "#{Rails.root}/tmp/uploads"    end  end  

Another thing is that I tried to to a simple storage: :file in production, avoiding the S3 upload stuff, and it fails too.

Any idea?

UPDATE!

I added the authenticity_token: true in the form and it doesn't raise the exception I mentioned above. However, something weird is happening:

  • When I don't select an image from the form, the POST is done remote:

Processing by ProductsController#create as JS

  • When I select an image in the form, the POST is not done remote:

Processing by ProductsController#create as HTML

UPDATE 2!

This is the generated html for the form tag:

<form class="product-form" id="new_product" enctype="multipart/form-data" action="/seller/products" accept-charset="UTF-8" data-remote="true" method="post">    <input name="utf8" type="hidden" value="✓">    <input type="hidden" name="authenticity_token" value="SOME STUFF">     </form>  

Function parameter and different use as a object and SQL query

Posted: 14 Oct 2016 06:05 AM PDT

I am trying to build a function with a parameter and then use this parameter all over my function but I have some issue, I don't know how to convert it for this two different cases

def html_append(attribute)  [...].order(attribute: :asc)  [...]   [...]current_object.attribute[...]   

Do you have any lead? Have a great day.

Jonathan

Evaluating 2 ActiveRecord .where queries with logical operators in rails

Posted: 14 Oct 2016 06:02 AM PDT

I'm trying to implement a basic messenger system in a rails app. I was following a guide who proposed the following code in the create method.

    if Conversation.between?(params[:sender_id], params[:recipient_id]).present?          @conversation = Conversation.between?(params[:sender_id],params[:recipient_id]).first      else          @conversation = Conversation.create!(conversation_params)      end      redirect_to conversation_messages_path(@conversation)      end  

The objective is to only create a new conversation when there was none already open for the same two users, otherwise it creates a new one.

I've tried to use this code but it returns an error:

undefined method `between?' for nil:NilClass  

despite @conversations is not nil. The method between? doesn't seem to be available.

I've tried to write a convoluted ActiveRecod query below

    @session = Conversation.where('recipient_id = params[:sender_id] and sender_id = params[:recipient_id]') + Conversation.where('recipient_id = params[:recipient_id] and sender_id = params[:sender_id]')  

but it raises

PG::UndefinedColumn: ERROR: column "params" does not exist LINE 1: ...ons".* FROM "conversations" WHERE (recipient_id = params[:se... ^ : SELECT "conversations".* FROM "conversations" WHERE (recipient_id = params[:sender_id] and sender_id = params[:recipient_id]) LIMIT $1  

my whole controller below:

class ConversationsController < ApplicationController    def index      @users = User.all      @profiles = Profile.all      @conversations = Conversation.all   end    def create        @session = Conversation.where('recipient_id = params[:sender_id] and sender_id = params[:recipient_id]') + Conversation.where('recipient_id = params[:recipient_id] and sender_id = params[:sender_id]')        if @session.present?        @conversation = @session.first      else        @conversation = Conversation.create!(conversation_params)      end        redirect_to conversation_messages_path(@conversation)  end    private    def conversation_params      params.permit(:sender_id, :recipient_id)  end  end  

and my Conversation model

class Conversation < ApplicationRecord      belongs_to :sender, :foreign_key => :sender_id, class_name: 'Profile'    belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'Profile'    has_many :messages, dependent: :destroy    validates_uniqueness_of :sender_id, :scope => :recipient_id      scope :between, -> (sender_id,recipient_id) do    where("(conversations.sender_id = ? AND conversations.recipient_id = ? ) OR (conversations.sender_id = ? AND conversations.recipient_id = ? )", sender_id,recipient_id, recipient_id, sender_id)    end    end  

Finally my view

    <h1>conversations</h1>    <div class="ui segment">      <h3>Mailbox</h3>      <div class="ui list">          <div class="item">              <% @conversations.each do |conversation| %>                  <% if conversation.sender_id == current_user.id || conversation.recipient_id == current_user.id %>                      <% if conversation.sender_id == current_user.id %>                      <% recipient = User.find(conversation.recipient_id) %>                  <% else %>                      <% recipient = User.find(conversation.sender_id) %>                  <% end %>              <%= link_to recipient.firstname,   conversation_messages_path(conversation)%>              <% end %>              <% end %>          </div>      </div>  </div>    <div class="ui segment">      <h3>All Users</h3>      <div class="ui list">          <% @users.each do |user| %>          <% if user.id != current_user.id %>          <div class="item">              <%= user.firstname %>              <%= link_to "Message me!", conversations_path(sender_id: current_user.id, recipient_id: user.id), method: :post %>          </div>          <% end %>          <% end %>      </div>  </div>  

I was hoping someone can provide a solution and an explanation on why between? is not available. Thanks

Rails - Prevent post request creating multiple rows from an array whilst still keeping the data

Posted: 14 Oct 2016 05:06 AM PDT

I'll start with my controllers create action:

def create      this_order = params[:line_items]      this_order.each do |this|          @order = Transaction.new          @order.shopifyid = params[:id]          @order.vartitle = this['variant_title']          @order.save      end  end  

If you're unfamiliar with the ShopifyAPI, this is just looking through an order JSON and creating an internal row of each order in my transactions table, at the moment it just stores the order id and then goes into a line_items array and gets the variant title to store with it.

It works fine, but of course this creates a new row for each item in an order, when i actually want it to give me one order with all the items in it.

Is this a case of converting my table columns into an array of hashes? Or am i missing another way to do this?

Alternative for Multiple ajax to get data rails

Posted: 14 Oct 2016 07:28 AM PDT

I have 4 tabs on my page:

MY Queue | Today | Followup | Upcoming

on page load i fire 4 ajax calls to get data from controller for all these tabs and once i get data i create list for each of the tabs.

But as ajax is asynchronous i get anomalies in my data, are there any better ways to achieve this.

i have 4 ajax calls similar to below call:

$.ajax({                      url: '/opd_clinical_workflow/get_appointment_lists',                      dataType: 'json',                      data: {                          current_date: current_date,                          department_id: current_department,                          doctor: current_doctor,                          status: current_status,                          source: "list",                          q: $( "#search_appointment").val(),                      },                      success: function(res){                          console.log(tab,res)                          _this.updateMyQueueSummary(res,id,tab);                      },                      error: function(err){                          console.log(err);                      }                 });  

updateMyQueueSummary: Puts data in respective tabs

createSummaryAppointment: Creates html for me and is called in updatesummary

Validates data of other model when accepts_nested_attributes_for is used

Posted: 14 Oct 2016 03:56 AM PDT

I have belongs to and has many relation.

The problem is that I need to check if score field from nested attributes is less 0, it should not save records instead return to form with error message.

The code I am trying is:

class QuizAttempt < ActiveRecord::Base      has_many :quiz_answers    accepts_nested_attributes_for :quiz_answers, reject_if: :invalid_score      validate :score_greater_than_zero      private      def score_greater_than_zero      errors.add(:quiz_answers, 'must greater than 0') if invalid_score(attributes)    end      def invalid_score(attributes)      attributes['score'].to_i > 0    end  end      class QuizAnswer < ActiveRecord::Base    belongs_to :quiz_attempt  end  

The form field looks like that containing array:

name="quiz_attempt[quiz_answers_attributes][5][score]"  

What is the difference between Employee.last and Employee.last.decorate in Rails?

Posted: 14 Oct 2016 03:31 AM PDT

I didn't find any answer for this question after google. Please can anyone explain the difference between these two.

How can I use category name for slug, using Friendly_id and active admin?

Posted: 14 Oct 2016 06:33 AM PDT

Hi I'm using the friendly_idgem for the categoriessection of my App.

I'm Using active adminfor the backend and If I log in to the admin panel to create a new Category there is now two inputs, one for category name and the other for slug (see photo below)

enter image description here

Do I have to always add the slug to categories? How can I fix it up so rails use the :name for the friendly_Idinstead of the :slug ?

I followed the documentation for friendly_id but I couldn't find anything good on how to integrate it with active admin.

in the category.rb model I have this code

class Category < ActiveRecord::Base       has_many :products, :dependent => :nullify       extend FriendlyId     friendly_id :name, use: [:slugged, :history, :finders]    end  

This is the categories_controller.rb

class CategoriesController < ApplicationController   before_action :set_category, only: [:show, :edit, :update, :destroy]  def index   @categories = Category.all  end    def show   @meta_title = "MyPage - #{@category.name}"   @meta_description = "MyPage - #{@category.name}"   @products = @category.products   @images  = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]   @random_no = rand(5)   @random_image = @images[@random_no]  end    private     def set_category    @category = Category.includes(:products).find(params[:id])   end     def category_params    params.require(:category).permit(:name, :slug)   end   end  

This is the code in the config/initializers/friendly_id.rb

FriendlyId.defaults do |config|     config.use :reserved     config.reserved_words = %w(new edit index session login logout users admin  stylesheets assets javascripts images)       config.use :finders     config.use :slugged     config.slug_column = 'slug'     config.sequence_separator = '-'     config.use Module.new {    def should_generate_new_friendly_id?      slug.blank? || title_changed?    end  }  end  

If I change my app/admin/category.rb code to what is below.

ActiveAdmin.register Category do     permit_params :name     extend FriendlyId    friendly_id :name, use: [:slugged, :history, :finders]     end  

The server throws back this error .rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/friendly_id-5.1.0/lib/friendly_id.rb:91:in 'singleton class': undefined method 'relation' for class 'ActiveAdmin::ResourceDSL' (NameError)

So what do I have to do to let rails only use the category name for a slug and not have to type the name in twice as slug and name?

after_sign_in_path_for not working

Posted: 14 Oct 2016 02:54 AM PDT

I am trying to sign in user with a 'js' request. Earlier it was working fine. But after I tried to change the layout of admin panel, the redirection for after_sign_in_path_for resource stopped. It does sign in user and if i refresh the page, it takes me to the desired location. But not immediately.

Here are my logs

Started POST "/users/sign_in" for 127.0.0.1 at 2016-10-14 15:10:15 +0530 Processing by SessionsController#create as JS Parameters: {"utf8"=>"✓", "user"=>{"email"=>"client@gmail.com", "password"=>"[FILTERED]"}}

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["email", "client@gmail.com"]] CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["email", "client@gmail.com"]]

(0.2ms) BEGIN

SQL (0.3ms) UPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5 [["last_sign_in_at", "2016-10-14 09:39:42.565924"], ["current_sign_in_at", "2016-10-14 09:40:16.049440"], ["sign_in_count", 34], ["updated_at", "2016-10-14 09:40:16.052657"], ["id", 3]]

(20.2ms) COMMIT

Completed 200 OK in 121ms (Views: 0.4ms | ActiveRecord: 22.2ms)

Here's My controller Code:

resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")  set_flash_message(:notice, :signed_in) if is_flashing_format?  sign_in(resource_name, resource)  message = I18n.t 'devise.sessions.signed_in'  yield resource if block_given?    if request.xhr?    return render :json => {:success => true, :login => true, :data =>  {:message => message}}  end    respond_with resource, location: after_sign_in_path_for(resource)  

Thank You

How To Skip PaperTrail Version on ActiveRecord Callback

Posted: 14 Oct 2016 03:11 AM PDT

Currently, I've implemented a Rails Data Auditing app using PaperTrail. I've added a new version for every create, update and destroy actions.

The thing is that, I have an after_create callback in my model in which I want the PaperTrail to ignore it.

For now, when I create a new record, there are two versions are created. One is of the create event, and other one is of the update event of my callback.

What I want is to just one version to be created here, a version of the create event.

To be specific, my callback is just to add a slug, an alias is, to my record in which I do not want to show such this change to the user.

I wonder if there is a way to do so.

Any suggestions are appreciated.

Thanks,

Rails root page not displayed on heroku app

Posted: 14 Oct 2016 02:48 AM PDT

I have created an app in RoR, but the problem is that i am not able to get the root page that is "posts#index" on heroku but i am able to view it on rails local server. The route file is

Rails.application.routes.draw do    resources :posts    root "posts#index"    get "/posts/new" => "posts#show"  end  

I am using sqlite3 for development and test & postgreSQL for production.
And the heroku log contains error like

  1. Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running gem install bundler
  2. Include 'rails_12factor' gem to enable all platform features.
  3. No Procfile detected, using the default web server. We recommend explicitly declaring how to boot your server process via a Procfile.

A thanks in advance.

Carriewave doesn' upload versions to S3

Posted: 14 Oct 2016 02:46 AM PDT

I use carrierwave gem in my Rails 3.2 project. User can upload some document files. My uploader uploads documents to S3 and also creates 2 previews for each document, if the document allows to create preview. The uploader supports 2 types of preview: jpg and png. With JPG preview everything works well. With PNG preview the behavior is strange! If I upload 10 times the same PNG file, maybe 3 uploads are correct, others are processed without creation of versions.

After some investigation I've found that the versions are created! They remain in temporary location, e.g. "/uploads/tmp/20161014-1105-6852-1643". If the document is uploaded successfully, the temporary directory is deleted. But if the upload fails, the temporary directory remains there. The versions inside are perfectly done but not uploaded to S3. There is absolutely no error or exception or warning reported. Nothing is in log file, nothing is reported by RubyMine dev environment.

Anybody can help me???

GEM File:

gem 'rmagick', '2.13.2'  gem 'carrierwave', '0.8.0'  gem 'fog', '1.24.0'  gem 'mime-types', '>= 1.16'  

Document Model:

class Document < FileSystemItem     mount_uploader :data, DocumentUploader     ...  end  

My Uploader:

class DocumentUploader < CarrierWave::Uploader::Base       include CarrierWave::RMagick    include CarrierWave::MimeTypes      version :previewpng, :if => :can_make_preview_png? do      process :resize_to_fit_format => [512, 512, 'png', :transparent]        version :icon do        process :resize_to_fit_format => [64, 64, 'png', :transparent]      end    end      version :previewjpg, :if => :can_make_preview_jpg? do      process :resize_to_fit_format => [512, 512, 'jpg', :white]        version :icon do        process :resize_to_fit_format => [64, 64, 'jpg', :white]      end    end      def can_make_preview?(for_file)      true  # simplified here for this purpose      end      def can_make_preview_jpg?(for_file)      return false unless can_make_preview?(for_file)      !png_preview? for_file    end      def can_make_preview_png?(for_file)      return false unless can_make_preview?(for_file)      png_preview? for_file    end      def png_preview?(for_file)      /eps|png/ =~ for_file.filename.split('.').last    end      def resize_to_fit_format(width, height, format, background = :checkerboard)      manipulate! :format => format do |img|        img.tap do |i|          i.resize_to_fit!(width, height) if i.columns > width || i.rows > height            if background == :white            background_image = Magick::Image.new(width, height) { background_color = 'white' }          elsif background == :checkerboard            background_fill = Magick::TextureFill.new(checkerboard)            background_image = Magick::Image.new(width, height, background_fill)          end            unless background_image.nil?            i.composite!(background_image, Magick::NorthWestGravity, Magick::DstOverCompositeOp)            destroy_image(background_image)          end        end      end    end      def checkerboard      @@checkerboard ||= Magick::Image.read('pattern:checkerboard').first.modulate(2.0)    end      ...  end  

Rails - expand table row on click of link_to

Posted: 14 Oct 2016 04:22 AM PDT

in my app that I am building to learn rails and js, I have this case re. to expanding a table row to show a partial. to help understand, see this image:

enter image description here

The CSS for edit-tag can set to display "none"; this is the table:

<table id="tags" class="table table-hover" style="background-color: white; word-wrap: break-word; font-size: 0.9em;" >  <thead>      <tr>          <th>Tagged content</th>          <th>as</th>          <th>in</th>          <th></th>      </tr>  </thead>  <tbody>      <% object.tags.each do |tag| %>          <% unless tag.content.blank? %>          <tr>              <td style="word-wrap: break-word;"><%= link_to tag.content, [object, tag], method: :patch %></td>              <td><%= tag.tagtype.name %></td>              <td><%= tag.tagtype.typeoftag %></td>              <td><%= link_to '', [object, tag], method: :delete, data: { confirm: 'Please confirm deletion!' }, :class => "glyphicon glyphicon-trash" %></td>          <tr id='edit-tag'>              <td colspan="5"><%= render 'tags/tag_update' %></td>          </tr>          </tr>          <% end -%>      <% end -%>  </tbody>  

I created this function in JS yet it uses ID

$(function()  {  var DisplayTagEdit = document.getElementById('DisplayTagEdit');  DisplayTagEdit.onclick = function() {      var edittag = document.getElementById('edit-tag');      if (edittag.style.display !== 'none') {          edittag.style.display = 'none';      }      else {          edittag.style.display = 'block'      }  }  });  

So my issues are:

  • when creating a JS using an ID (like above) it will relate to all rows in the table. How to make it unique?
  • when clicking the link for another row (that is not expanded), the open rows need to be imploded/closed. How to do that?
  • may be I am taking a complete wrong approach. If so, let me know how i can make it easier/more simple?

Stuck with ruby new test_install

Posted: 14 Oct 2016 06:17 AM PDT

I'm starting to learn Ruby On Rails from Coursera. I am completely new to this and I do not know any command line/Linux/Unix etc.

While running ruby new test_install, I am getting the following error:

error1

I already read posts related to this error on stackoverflow. Some people suggested doing this:

gem source -r https://rubygems.org/  gem source -a http://rubygems.org/  

But then this gave the following error: enter image description here Please see if anyone can help.

Rails, syntax error?

Posted: 14 Oct 2016 05:03 AM PDT

I'm following this tutorial to create a messaging system in rails. https://medium.com/@danamulder/tutorial-create-a-simple-messaging-system-on-rails-d9b94b0fbca1#.lhwzqr92b

My main issue now is that I'm getting a syntax error unexpected '?' related to the following scope validation in my Conversation model:

  scope :between, -> (sender_id,recipient_id) do    where("(conversations.sender_id = ? AND conversations.recipient_id = ? ) OR (conversations.sender_id = ? AND conversations.recipient_id = ? )", sender_id,recipient_id, recipient_id, sender_id)    end  

It's supposed to check if a conversation between two users already exists so we can make sure only a conversation exists between 2 users.

I've been trying fiddling with the code taking out some parenthesis and googling only gives me general answers. I'm going crazy here. Could someone help to point out the syntax error?

No comments:

Post a Comment