Thursday, September 29, 2016

Send_file open file in browse instead of download it | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Send_file open file in browse instead of download it | Fixed issues


Send_file open file in browse instead of download it

Posted: 29 Sep 2016 07:55 AM PDT

please tell me how it's work, coz i'm don't understand... My simple code

Route

 get 'download' =>'pages#download'  

My actinon

def download    send_file "#{Rails.root}/public/downloads/robots.zip", :type=>"application/zip"  

and download link

<%= link_to "download", download_path%>  

So, when i'm clicking on the link I get this http://joxi.ru/GrqvQ3xHlbaYmz it's seems like browser try to show zip file content... But when I open my action from browser (or refresh page) it's work fine

Why it's don't work when I click on the link generated by link_to (it open http://joxi.ru/GrqvQ3xHlbaYmz ?

How to learn Ruby on Rails *Source Code*? [on hold]

Posted: 29 Sep 2016 07:50 AM PDT

There are many tutorial on the web teach about how to use Ruby on Rails
But I can't find any tutorial about how Ruby on Rails work under the hood

I really want know how Ruby on Rails work under the hood,
someday may even contribute code into Ruby on Rails
(for now seem like there are long way to go)

Where should I start?

Learn about what is gem? and then what is rack? and then what?
Any Suggestion? Thanks

Am I asking the wrong question?
or I am posting a question at a wrong place?
4 downvote within 1 minute? really??

Rails routes resources - add extra param on all routes

Posted: 29 Sep 2016 07:49 AM PDT

I wanna generate some routes for my scaffold, but in some way that all of then looks something like:

/companys/:type  /companys/:type/new  /companys/:type/:id/edit  

so I can catch that "type" param on my controllers. I don't wanna do it manually... Is there some way to easily add that :type param? Thanks!

Retrieving attributes of associated object Rails

Posted: 29 Sep 2016 07:39 AM PDT

I have a post that has many comments. Comments have a body and a title

 => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]>   2.3.0 :005 > Post.first.comments    Post Load (0.5ms)  SELECT  "posts".* FROM "posts"  ORDER BY "posts"."id" ASC LIMIT 1    Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]   => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]>   2.3.0 :006 > Post.first.comments.body    NoMethodError:   Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]  undefined method `body' for #<Comment::ActiveRecord_Associations_CollectionProxy:0x007f9bef0a33a8>  

In the code above you can see that I try to get the body attribute from the post that has a comment, but I get a no method exception. How do I retrieve the associated objects data in these types of situations?

SQLite3::BusyException: database is locked: INSERT INTO

Posted: 29 Sep 2016 07:54 AM PDT

When I run this piece of code with a task, it works

task :importGss => :environment do      Gss.delete_all      file = Rails.root + "app/assets/CSVs/gss.csv"      csv_text = File.read(file)      puts csv_text.size      csv = CSV.parse(csv_text, :col_sep => ';', :headers => true)      csv.each do |row|      Gss.create!(row.to_hash)  end    

When I run it with a MVC, I have the following message :

ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:

I have put the above code in a function in the Gss model. The import is launched from the browser with a GET that is routed to the controller that calls the model import function When the import is finished, the complete list of record should then be returned to the view. the csv file has 4k rows. The process of importing takes time and it seems that after precisely 60 seconds the GET is resend. Can someone explain me how to avoid this resending that crashes the import ?

Get list of all regitered connections

Posted: 29 Sep 2016 07:28 AM PDT

http://stackoverflow.com/a/36230416/5381547

http://stackoverflow.com/a/32945949/5381547

Those answers don't help me.

I want to get list of all registered connections to my ActionCable. I tried

Redis.new.pubsub("channels", "action_cable/*")

and

ActionCable.server.connections.length,

but they both return []. So for now I'm using something like

def connect    self.uuid = SecureRandom.uuid      players_online = REDIS.get('players_online') || 0    players_online = players_online.to_i    players_online += 1    REDIS.set('players_online', players_online)  end    def disconnect    players_online = REDIS.get('players_online').to_i    players_online -= 1    REDIS.set('players_online', players_online)  end  

But I know that this is a totaly not Rails-way. Is there any possibility to get a list of all registered connections?

keep changed style by javascript after showing flash error message in ruby on rails

Posted: 29 Sep 2016 07:27 AM PDT

I have a div part in my HTML(erb), whose display is "none" at first. Then I change its style to "block" detecting the input values of datetimepicker.

I have succeeded to change the style, but the style reverses to "none" if the form gets flash error message shown after validation.

Is there any way to keep the style changed even after error message shows up.

Here is my code of javascript.

  $('.datetimepicker').on('dp.change', function(e) {       var x = document.getElementById("from").value;      var y = document.getElementById("to").value;      var date_y = Date.parse(y);      var date_x_day = Date.parse(x) + (1 * 86400000);        if (date_y > date_x_day) {        $('#hotel').fadeIn(500);       } else {        $('#hotel').fadeOut(500);      }    });  

I tried to put the line below after "$('#hotel').fadeIn(500); " but it doesn't work.

document.getElementById('hotel').style.display="block";  

Could anyone tells me the best way??

Impossible to display the image uploaded with paperclip

Posted: 29 Sep 2016 07:54 AM PDT

I got a problem with paperclip, I just can't display the image who has been uploaded, here is my code :

images_controller.rb :

class ImagesController < ApplicationController    layout 'home2'    def new      @image = Image.new    end      def create      @image = Image.new(params[:images])      end      def post_params        params.require(:image).permit(:title, :description, :nickname, :creation)      end  end  

My migration generate with paperclip

class AddAttachmentCreationToImages < ActiveRecord::Migration    def self.up      change_table :images do |t|        t.attachment :creation      end    end      def self.down      remove_attachment :images, :creation    end  end  

my model image.rb:

class Image < ApplicationRecord    has_attached_file :creation,      :styles => {        :large => "1000x1000>",        :medium => "500x500>",        :thumb => "300x300#"      }    validates_attachment_content_type :creation, content_type: /\Aimage\/.*\z/  end  

my view create.html.erb:

<h2 align="center">Post your own creation right here !</h2>  <br>  <div align="center">    <%= link_to 'Back', '/showcase', :class => "buttonShow" %>  </div>      <%= simple_form_for @image do |f| %>    <%= f.input :title, :required => true %>    <%= f.input :description, :required => true %>    <%= f.input :nickname, :required => true %>    <div align="center">    <%= f.file_field :creation, :required => true %>      <%= f.button :submit, "Post !", :class => "buttonShow1"  %>    </div>  <% end %>      <%= image_tag @image.creation.url(:thumb) %>  

and my routes.rb

Rails.application.routes.draw do    resources "images", only: [:new, :create]    resources "contacts", only: [:new, :create]    get 'contacts/contact'      #get 'images/crea'    #get 'images/post'      get 'auth/auth'      root "auth#auth"    #get 'contact' => 'contacts#contact'    get 'showcase/post' => 'images#create'    get 'showcase' => 'images#new'    get 'images' => 'images#new'    #get 'images/new' => 'showcase'    #resources "contacts", only: [:new, :create]    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  end  

I don't know why I can't upload any files, the display look like this : http://hpics.li/131d722

I just tried with a new project and it work but with this code , it doesnt work, I think the path of the image is wrong maybe, but im not sure and I don't know how to fix it.

Thanks in advance for your help.

Display filters prams when selected

Posted: 29 Sep 2016 07:23 AM PDT

I m making an rails app. I have search function with params and i want to display in my view filters params when they are slected but i dont know how i can do that.

Image is better than words so i want this http://img4.hostingpics.net/thumbs/mini_398032filterparams.jpg or image 2

camping_controller.rb

  def resultnohome            if params[:query].blank?              redirect_to action: :index and return            else              @campings = Camping.searchi(params[:query], params[:handicap], params[:animaux])            end    end  

resultnohome.html.erb

<%= render 'searchfilter', camping: @camping %>  

_searchfilter.html.erb

<%= form_tag(resultnohome_path, method: :get) %>    <%= text_field_tag :query, params[:query], class:"SearchFilter", placeholder:"Ex : Vendée, Corse..." %>    <li><p><span class="IcoHandi" aria-hidden="true"></span> Accès handicapé : <%= check_box_tag :handicap, "oui", !!params[:handicap], :class => "handicap" %></p></li>    <li><p><span class="IcoPets" aria-hidden="true"></span> Animaux acceptés : <%= check_box_tag :animaux, "oui", !!params[:animaux], :class => "animaux" %></p></li>    ...    <%= submit_tag "Appliquer les filtres", class:"btn btn-danger2", name: nil %>  <% end %>  

So my question is : How i can do that ? Thanks for your help !

Rails: belongs_to twice on same field

Posted: 29 Sep 2016 07:23 AM PDT

Please, anyone know, can I declare relation belongs_to twice to same field?

For example:

class Notice < ApplicationRecord    belongs_to :avia, foreign_key: 'ticket_id', class_name: 'AviaTicket'    belongs_to :bus, foreign_key: 'ticket_id', class_name: 'BusTicket'  end  

In this way, I have use ticket_id twice for different models. And on belongs_to side its doen't work, but on otherside(AviaTicket, BusTicket) works fine.

Rails Sunspot - not working search

Posted: 29 Sep 2016 07:06 AM PDT

I added a sunspot gem into my rails app and my model looks like this:

class Lab < ApplicationRecord      searchable do          text :name      end  end  

I run the commands as the docs said (with reindex command included).

After doing:

@search = Lab.search do       fulltext "laboratory"  end  @results = search.results  

the @results is an empty array, and I do have a record with name containing "laboratory".

I do not see any error, so what did I do wrong?

Bind error message on another attribute

Posted: 29 Sep 2016 07:08 AM PDT

I have the following validation rule in a model

validates :csv_fingerprint, uniqueness: { message: "CSV was already uploaded." }  

In the form view (simple_form), the following code generates the file upload field:

= f.input :csv, as: :file  

The validation works, but the error message is not shown at the upload field. I think, the reason is, that the validation is for :csv_fingerprint and the form field is :csv.

How can I tell the validation rule, that the message should be displayed at the :csv field?

Rails - two forms in one (ShopifyAPI)

Posted: 29 Sep 2016 07:33 AM PDT

Part of the app i'm developing involves a form which has to create a product on the users shopify store and also create a row in my own database for an identical product (with a few extra bits of information).

Where i'm struggling is with the form itself, i can do this with a html based form, but i can't get a single ruby form to do both jobs. A shortened version of my controller create code is as follows;

def create      @item = Item.new      @item.item_title = params[:item_title]      @item.item_profit = params[:item_profit]      @new_product = ShopifyAPI::Product.new      @new_product.title = params[:item_title]      @new_product.save      @item.save  end  

So as you can see i'm using the same params to set values for both the shopify product and the product in my own db. The HTML form looks like this:

<form action="/items/submit" >    <input type="text" name="item_title">    <br>    <input type="text" name="item_profit">    <br>    <br>    <input type="submit"/>  </form>  

And it works fine, but how do i convert this into a ruby form that does the same job?

Add a title to my select_tag

Posted: 29 Sep 2016 07:46 AM PDT

I am trying to put a title to my select_tags I would like to have something like Select a user and then all the users appear below... for now I have the name of the first user... I don't want that... Any suggestion? I can't find anything working with my view...

thanks for your help

=form_tag tutos_path, :method => 'get' do           =select_tag :select, options_for_select(User.order('nickname ASC').all.map{|u| u.nickname}, params[:select])          =submit_tag "Select", class:"btn btn-xs btn-default btn-search"  

Ruby on Rails error when validates_uniqueness_of using collection_select

Posted: 29 Sep 2016 06:59 AM PDT

First, sorry for my bad English. I'm still learning.

I have 3 tables in my DB:

Problem

  • has_many :registers
  • has_many :solutions, through : :registers

Solution

  • has_many :problems
  • has_many :problems, through : :registers

Register

  • belongs_to: problem
  • belongs_to :solution

The system is working well. I am able to insert new data in all of the 3 tables.

In the views for the table/model Register, to select problems and solutions, I make use of collection_select, like this:

= collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })  

The problem only appears when I try to add this validation to Register:

validates_uniqueness_of :student_id , scope: :course_id  

Then I get:

> undefined method `map' for nil:NilClass   > = collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })  

And I dont know why.

So, I tried to do the validation by the controller:

def create    @register = Register.new(register_params)    problem_id = @register.problem_id     solution_id = @register.solution_id    if Register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])      render 'new'    else      @register.save      respond_with(@register)    end  end  

But the error remains.

I believe that the cause is the collection_select, but I don't know how to solve it.

Saying one more time, I am able to persist date in all the 3 DB tables. But when I try to avoid duplication, the error appears.

Confirm popup not working

Posted: 29 Sep 2016 06:20 AM PDT

I have a problem as the confirm popup is not showing, when i use my delete button. The deleting works fine, i just dont get the "are you sure" popup first.

I have tried different variantions of this code, without any luck. I think i have the confirm part correct, but perhaps not. What am i missing here?

<%= link_to t('common.delete'), car_path(@current_work_context, car), :method => :delete, :confirm => t('common.are_you_sure'), :class => "btn btn-danger btn-xs" if car.deletable? %>  

Ajax fires up multiple times unless page is Reloaded, Rails 4 and Bootstrap

Posted: 29 Sep 2016 06:10 AM PDT

I have simple app with index and show pages. Pretty simple code and etc. Simple registration that is handled with Devise gem.

In index page I have such Bootstrap modal for registration:

     <div class="modal fade" id="register" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">                          <div class="modal-dialog log-modal">                              <div class="modal-content">                            <div class="user-registration-content">                                <div class="modal-header clearfix">                                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>                                  <h4 class="modal-title pull-left"><%= t('user_creation') %> <!--Lietotāja izveide --></h4>                                    <%= link_to '#',:class=>"pull-right",:id=>"login-path-link" do %>                                                   <span><%= t('already_registered') %> <!--Jau esi reģistrēts --></span>                                      <%end%>                              </div>                                <div class="modal-body">                                  <span><%= t('please_fill_form') %></span>                                    <%= form_for(@user, :html => {:id=>"sign_up_user" ,:class=>"registration-form-modalc","data-parsley-validate" => true},remote: true, format: :json,as: @user, url: registration_path(@user)) do |f| %>                                        <div class="form-group">                                                                               <%= f.text_field :name,:class=> "user-input form-control", :id=>"user-name",autofocus: true ,:placeholder=> t('username_2'),:required => true,:'data-parsley-minlength'=>"3"%>                                                                          </div>                                        <div class="form-group">                                                                    <%= f.password_field :password,:id=>"passwordis",:class=> "user-input form-control", autocomplete: "off" ,:placeholder=> t('new_password'),:required => true,:'data-parsley-minlength'=>"8" %>                                                                           </div>                                        <div class="form-group">                                          <%= f.password_field :password_confirmation, :id=>"password-again",:class=> "user-input form-control", autocomplete: "off" ,:'data-parsley-equalto'=>"input#passwordis",:placeholder=> t('new_password_2'),:required => true,:'data-parsley-minlength'=>"8"%>                                          <%= f.hidden_field :role, :value => "user"%>                                          <%= f.hidden_field :country_id, :value => @location.id%>                                                                                              </div>                                        <div class="form-group">                                         <%= f.email_field :email ,:class=>"user-input form-control" ,:'data-validatess' => '/blocked/checkemail',:id=>"emailito",:placeholder=> t('email'),:required => true%>                                            <h3 id="email-taken-message" style="display:none;margin-left:140px;color:red;padding-top:7px;"> <%= t('email_not_available') %> </h3>                                                                                                                                                      </div>                                        <%= f.hidden_field :humanizer_question_id %>                               <div class="question-content" style="position:relative;top:1px;">                                  <span class="question"><%= t('question') %>:</span>                                  <span class="answer"  >                                   <%= f.label :humanizer_answer, @user.humanizer_question %>                                  </span>                                  <div class="form-group" style="margin-bottom:21px;">                                 <span class="question" style="margin-top:8px;"><%= t('answer') %>: *</span>                                                                   <%= f.text_field :humanizer_answer ,:class=> "form-control",:required => true, :id=>"answer"%>                                </div>                                                                     </div>                            <%= f.submit t('confirm'),:class=> "blue-button btn btn-default"%>                                    <div class="squared">                                        <%= f.check_box :terms_of_service,:id=>"accept",:required => true,:type=> "input"%>                                      <!--<input type="checkbox" value="" id="accept" name="check" /> -->                                      <label style="left: 0px;"for="accept"><span><%= t('read_and_agree') %> <!--Izlasīju un piekrītu  -->                                          <%= link_to t('rules_2'),help_path, :target=>'_blank' %>                                      </span>                                        </label>                                      </div>                                    <div class="squared">                                        <%= f.check_box :not_a_robot,:id=>"user-status",:required => true, :type=> "input"%>                                      <label style="left: 0px;"for="user-status"><span><%= t('not_robot_confirm') %></span></label>                                    </div>                                      <div class="squared">                                   <%= f.check_box :im_old,:id=>"user-age",:required => true, :type=> "input"%>                                        <label style="left: 0px;"for="user-age"><span><%= t('already_adult') %></span>                                        </label>                                   </div>                                </div>    <%end%>    </div>                   </div>            </div>      </div>  

At the end of the Application_layout file:

 <%= javascript_include_tag "application" %>          <script src="/assets/lightbox.js"></script>      <script src="/assets/bootstrap.min.js"></script>      <%= javascript_include_tag "co.js" %>        <script src="/assets/scripts.js"></script>    

Registration process is handled with remote => true.

script.js:

$(document).ready(function() {    return $("form#sign_up_user").on("ajax:success", function(e, data, status, xhr) {                   $(".user-registration-content").hide();               $(".registration-sent").show();        }).on("ajax:error", function(e, xhr, status, error) {          alert("Error user registration");      });  });  

Application.js file:

//= require jquery  //= require jquery_ujs  //= require jquery.remotipart  //= require turbolinks  //= require parsley  //= require_tree.  

Problem: Unless I refresh page before triggering modal and filling in form, submitting form triggers 2 identical requests. If I visit show page and then come back to index page to register form submitting triggers 4 identical requests.

Basically, each time user visits show page number of requests increases by 2. At the end requests can go up to 10 and more. After reloading page everything is back to normal.

The same problem occurs when I click on page logo that sends to root_path that is basically the same index page. And the cycle continues.

What I tried:

1) Deleted every other script from scripts.js file except the script for handling registration process (see above for script)

2) Changed all click elements to .one('click', function()

3) Removed every other Bootstrap modal from my page so the conflict possibility could be excluded.

4) Double checked page source for index and show page to check if script.js file is called just once.

5) I have cleared tmp/assets folder.

6) Problem happens on all browsers.

Note: This problem occurs on every ajax request. In my app I have lot of modals with ajax submitting and every of them have the same problem unless I reload page each time.

I have run out of options to try.

Thank you in advance for any help.

Rails 5 - limit selection of associated object

Posted: 29 Sep 2016 07:18 AM PDT

In my app that I am building to learn RoR, I have Annotation (for documents of a document type) with tags (much like posts and comments). When adding a tag to an annotation, I want to limited the possible types of the tag to those tag types that have the same document type as the document type of the annotation.

To reduce the list of tag types I already use a scope to get active tag types. Like so:

<%= f.association :documenttype, :collection => Documenttype.active.order(:name) %>  

with this scope

scope :active, -> { where(active: true) }  

How can I extend it for matching document types? If with a scope, how; if not, what approach should I take then?

Rails - NoMethodError undefined method `>=' for nil:NilClass

Posted: 29 Sep 2016 06:33 AM PDT

I'm getting the above error in my model. Here's the model code -

Booking.rb

    class Booking < ActiveRecord::Base        belongs_to :event      belongs_to :user        validates :quantity, presence: true, numericality: { greater_than: 0 }      validates :total_amount, presence: true, numericality: { greater_than: 0 }      validates :event, presence: true, numericality: {greater_than_or_equal_to: 0 }        before_validation :set_default_values_to_greater_than_or_equal_to_zero        def set_default_values_to_greater_than_or_equal_to_zero          self.quantity >= 1          self.total_amount >= 0            self.event.price >= 1    unless self.event.is_free      end        def reserve(stripe_token)          # Don't process this booking if it isn't valid          self.valid?            # We can always set this, even for free events because their price will be 0.          #self.total_amount = booking.quantity * event.price                    # Free events don't need to do anything special                  if event.is_free?                  save!                    # Paid events should charge the customer's card                  else                        begin                          self.total_amount = event.price * self.quantity                          charge = Stripe::Charge.create(                              amount: total_amount,                              currency: "gbp",                              source: stripe_token,                               description: "Booking created for amount #{total_amount}")                          self.stripe_charge_id = charge.id                          save!                      rescue Stripe::CardError => e                      errors.add(:base, e.message)                      false                  end              end           

No comments:

Post a Comment