Wednesday, September 7, 2016

undefined method `id' for nil:NilClass on my style tags | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

undefined method `id' for nil:NilClass on my style tags | Fixed issues


undefined method `id' for nil:NilClass on my style tags

Posted: 07 Sep 2016 07:46 AM PDT

am having undefined methodid' for nil:NilClass` when i load my rails 4 app the error shows on this line

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <script src="https://unpkg.com/flickity@2.0/dist/flickity.pkgd.min.js"></script>    <%= csrf_meta_tags %>  

when i remove the style tag and javascript tag the page loads fine. am using rails 4

Creating a dynamic xlsx with the write_xlsx gem

Posted: 07 Sep 2016 07:42 AM PDT

I want to export a part of my db for the user as a .xlsx

I managed to create a static file and let the user download it, but that's not really the point.

The user should select the filter he wants and as a result the file should be created and downloaded directly through the browser.

my code looks something like this:

controller

def download_pdf    send_data generate_pdf,              type: "application/xlsx"  end    private    def generate_pdf    workbook = WriteXLSX.new('export.xlsx')      worksheet = workbook.add_worksheet      worksheet.write(0, 0, 'Status')    worksheet.write(0, 1, 'Auftragserstellungsdatum')    worksheet.write(0, 2, 'Debitor')      workbook  end  

the result would be a file and the content is just the name of the object

#<WriteXLSX:0x007fd9cf8aa290>  

I'm not sure if this is something write_xlsx specific or if I'm missing something obvious here.

How to remove duplicates from where in rails

Posted: 07 Sep 2016 07:34 AM PDT

so i have this code here

popular = Impression.select('impressionable_id, count(impressionable_id) as total').group('impressionable_id').order('total desc').limit(9)  @events = Event.where(id: popular.map(&:impressionable_id))  

However whats happening at the moment is that the @events is returning duplicate names. I'm wondering how to return them without returning names that match.

Any ideas would be great!

Rails - creating place with weekdays in one form

Posted: 07 Sep 2016 07:46 AM PDT

I created a model for a Place

class Place < ApplicationRecord      has_many :open_days, dependent: :destroy  end  

and a model for OpenDay:

class OpenDay < ApplicationRecord      belongs_to :place  end  

I want to be able to create a record of this place (what I have now is simple textfields) with day of the weeks (and hours) that the place is opened at.

My current form:

<%= form_for(@place) do |f| %>      <%= f.label(:name) %>      <%= f.text_field(:name, placeholder: "Place's name", class: "form-control") %>      <%= f.label(:street) %>      <%= f.text_field(:street, placeholder: "Street", class: "form-control") %>      <%= f.fields_for :open_days do |open_day| %>        <%= open_day.text_field :day %>      <% end %>      ....  <% end %>  

My new controller

def new      @place = Place.new      7.times do          @place.open_days.build      end  end  

I decided to go with a table (screen below) but I have absolutely no idea how to create a form for another model inside my existing form for @place. And what's more to be able to save multiple records using this form. Searched through SO but came with noting.

enter image description here

How remote: true work here without the js in controller and view file?

Posted: 07 Sep 2016 07:20 AM PDT

I am wonder how this is working alone?,,, I just add the remote: true here and ajax work fine.. I didnt create any js.erb in view file and did not add the format.js in the controller file... and it is working..how is that?

Anyone can explain this?

here is my code where I added the remote: true:

<% if current_user.id != user.id %>   <center>     <% if !current_user.following?(user) %>       <%= form_for(current_user.active_relationships.build, remote: true) do |f| %>        <div><%= hidden_field_tag :followed_id, user.id %></div>          <%= f.submit "Follow", class: "btn btn-primary" %>       <% end %>     <% else %>       <%= form_for(current_user.active_relationships.find_by(followed_id: user.id),        html: { method: :delete }, remote: true) do |f| %>         <%= f.submit "Unfollow", class: "btn" %>       <% end %>     <% end %>   </center>  <% end %>  

traditional rails commands don't work with ruby 2.3

Posted: 07 Sep 2016 07:23 AM PDT

I updated my ruby version to 2.3, and now when I try simple commands like rails new myApp I have this error message:

rbenv: rails: command not found    The `rails' command exists in these Ruby versions:    2.1.2    2.2.2  

Can you please help me with that, I can't find any answer online :)

No route matches {:action=>"edit", :controller=>"admin/progresses"} missing required keys: [:id]

Posted: 07 Sep 2016 07:31 AM PDT

While trying to create my edit link for my admin dashboard.I have this error... No route matches {:action=>"edit", :controller=>"admin/progresses"} missing required keys: [:id] Could you please explain me what's wrong?

here is my rake routes:

 admin GET    /admin(.:format)                         admin/dashboard#index           admin_progresses GET    /admin/progresses(.:format)              admin/progresses#index                            POST   /admin/progresses(.:format)              admin/progresses#create         new_admin_progress GET    /admin/progresses/new(.:format)          admin/progresses#new        edit_admin_progress GET    /admin/progresses/:id/edit(.:format)     admin/progresses#edit             admin_progress GET    /admin/progresses/:id(.:format)          admin/progresses#show                            PATCH  /admin/progresses/:id(.:format)          admin/progresses#update                            PUT    /admin/progresses/:id(.:format)          admin/progresses#update                            DELETE /admin/progresses/:id(.:format)          admin/progresses#destroy  

This is my views/admin/progresses/index.html.slim

.container    .row      h2 Pepito's Dashboard      br      = link_to "New article", new_admin_progress_path, class:'btn btn-success'      br      br        .dashboard        - @progresses.each do |progress|          .row               .col-xs-2              h4              = progress.title.capitalize            .col-xs-2              h4              = progress.date            .col-xs-5              h4                = truncate(progress.content, length: 90)            .col-xs-1              = link_to 'View', progresses_path, class:'btn btn-success'            .col-xs-1              = link_to 'Edit', edit_admin_progress_path(@progress), class:'btn btn-primary'            .col-xs-1              = link_to 'Destroy', "#", class:'btn btn-danger', method: :delete          hr  

This is my admin/progresses_controller.rb:

  class Admin::ProgressesController < Admin::ApplicationController        def index        @progresses = Progress.all      end        def new        @progress = Progress.new      end        def show        @progress = Progress.find(params[:id])        end        def create         @progress = Progress.new(progress_params)           respond_to do |format|           if @progress.save             unless params[:progress_attachments].nil?               params[:progress_attachments]['image'].each do |a|                 @progress_attachment = @progress.progress_attachments.create!(:image => a)               end             end             format.html { redirect_to admin_progresses_path, notice: 'Progress was successfully created.' }           else             format.html { render action: 'new' }           end         end         end         def edit         @progress = Progress.find(params[:id])       end         def destroy          @progress = Progress.find(params[:id])       end         def update        @progress = Progress.find(params[:id])          if @progress.update(params[:progress].permit(:title, :date, :content, :main_image, progress_attachments_attributes: [:id, :progress_id, :image]))            redirect_to progresses_path          else        render 'edit'          end      end           private         def progress_params          params.require(:progress).permit(:title, :content, :date, :main_image, progress_attachments_attributes: [:id, :progress_id, :image])       end      end  

Many thanks ! :)

Edit

Thanks everyone for all the answers!

= link_to 'Edit', edit_admin_progress_path(progress), class:'btn btn-primary' worked well !!

Why can't the post method in my Rspec test find the create action/route for my PostsController?

Posted: 07 Sep 2016 07:24 AM PDT

Hi I have an Rspec test:

require "rails_helper"        describe PostsController do         let(:user){create(:user)}      describe "POST #create" do         it "creates a Post" do         expect {post :create, post: attributes_for(:post)}.to change(Post, :count).by 1      end        end      end  

That is throwing the following error:

ActionController::UrlGenerationError:         No route matches {:action=>"create", :controller=>"posts", :post=>{:content=>"this is post content!"}}  

Which means it can't find the route right?

instead of passing :create as the first argument to post I have tried, passing it the route helper user_posts_path(user) <--- (this is the route for my posts create action), but I get pretty much the same error. Here is that attempt:

    it "creates a Post" do         expect {post user_posts_path(user), post: attributes_for(:post)}.to change(Post, :count).by 1      end  

which throws this error:

ActionController::UrlGenerationError:         No route matches {:action=>"/users/1/posts", :controller=>"posts", :post=>{:content=>"this is post content!"}}  

I've also attempted to pass in the id manually:

id: user.id  

as the second argument to post.

Here is the post_factory.rb since I am calling attributes_for(:post):

FactoryGirl.define do       factory :post do       content "this is post content!"      user    end  end  

My relevant rake routes:

user_posts GET    /users/:user_id/posts(.:format)        posts#index                   POST   /users/:user_id/posts(.:format)        posts#create     new_user_post GET    /users/:user_id/posts/new(.:format)    posts#new         edit_post GET    /posts/:id/edit(.:format)              posts#edit              post GET    /posts/:id(.:format)                   posts#show                   PATCH  /posts/:id(.:format)                   posts#update                   PUT    /posts/:id(.:format)                   posts#update                   DELETE /posts/:id(.:format)                   posts#destroy  

My PostsController create action is alive and well too.

So I know my route is there and I have tried passing the post method an explicit route instead of :create, but I still get the same error. I believe the problem is occurring because my routes are nested, but I need them to be nested, and would like to test them in that form so I can't change the nesting. I'm not sure what else to do, so I've come here for help. Thanks.

rails : Auto refresh a div

Posted: 07 Sep 2016 07:19 AM PDT

Sorry for my english i'm french. I'm a newbie in javascript, an i have a question :

I have a controller and a view with a div :

  def show      @requests = events.get_requests    end  

get_requests return all the requests in database (with a select) and i print in it in a div in my view

  <div class="party-block" id="requests">      <h4><%= t '.requests' %></h4>      <input type="button" value="<%= t '.refresh' %>" onClick="window.location.reload()" class="btn-sm btn-info">      <% @requests.each do |r| %>        <span class="request">          ...  

In this div i print all requests with other things. I want to automatically refresh this div with a js/jquery function, (for the moment i use a button for refresh) but i need to re-execute the code in my controller ?

I'm newbie in js. Thank you and sorry for my english ;)

Rails session variable doesn't get set until page reload

Posted: 07 Sep 2016 07:01 AM PDT

I have a session variable that I want to set when a user hits the devise login page. Unfortunately it doesn't take effect after I get redirected. Instead, I have to refresh the page and then I see the new variable.

I have tried a few things:

First I tried just setting the session variable session[:theme] = theme

Then I tried deleting the old key and setting a new key:

case theme    when 'theme1'      session.delete(:theme2)      session[:theme1] = true    else      session.delete(:theme1)      session[:theme2] = true    end  

Both of these require a page refresh after I am redirected to the login form. My server logs are showing that the session variable is being picked up but the browser just doesn't seem to want to change it until I reload.

Any help is greatly appreciated.

Updating "Receipt" comments on a Shopify Order using ShopifyAPI::Fulfillment

Posted: 07 Sep 2016 06:38 AM PDT

I'm trying to update the Receipt attribute of an order using ShopifyAPI::Fulfillment

I'm doing this:

fulfill = ShopifyAPI::Fulfillment.find(351144XXXX, :params =>   {:order_id =>  426199XXXX})  joe = fulfill.receipt  joe.response_status = "Accepted"  joe.response_comment = "Your order was received by Yo Mama"  fulfill.save  

It saves it, but the order doesn't keep the save.. Not sure what I'm doing wrong, if anything.

Regex for gsub in rails

Posted: 07 Sep 2016 06:39 AM PDT

I have a rails application where I am using kaminari for pagination.

Somehow kaminari is using wrong url for hyperlinks.

Right now I am looking for an easy fix which requires some regex & gsubbing.

I have this url from kaminari:

"/bookings/hotels//Pune?arrival_date=....."  

I want to replace this part - /hotels//Pune? with this - /hotels?

There could be any other string in place of Pune (it might change).

How should I do this ?

ruby on rails - if I have 2 models can I sort them both at once?

Posted: 07 Sep 2016 06:38 AM PDT

Let's say I have an Image model and a Video model how can I display them both in index by date

Rails 4: How to prevent jumping to index

Posted: 07 Sep 2016 06:45 AM PDT


I am fairly new to rails and currently coding my first app.
I created a search for the name of my tools model. It's passing the params correctly but constantly (jumps/redirects/passes the params) to the index of my model. How can I direct it to the tools#search site (site with the search form)?

A URL overview:

http://localhost:3000/search # Start  http://localhost:3000/tools?utf8=%E2%9C%93&search=&commit=Search # Directed to  http://localhost:3000/search?utf8=%E2%9C%93&search=&commit=Search # Where it should direct to  

A code overview:

Routes

get '/search' => 'tools#search'  

Tool Model

# Search   def self.search(search)    if search      where(["title LIKE ?", "#{search}"])    else      all    end  end  

Tools Controller

def search    @tools = Tool.search(params[:search]).order("created_at DESC")  end  

Search View (app/views/tools/search.html.haml)

= form_tag search_path, :method => 'post' do      = text_field_tag :search, params[:search]      = submit_tag "Search"    - @tools.each do |tool|      = image_tag tool.cover_filename.url      %h2= link_to tool.title, tool      %p= tool.subtitle      %p= link_to tool.user.try(:username), '/users/'+tool.user_id.to_s      %p= tool.impressionist_count      %p= link_to tool.get_upvotes.size, like_tool_path(tool), method: :get      %p= link_to "Favorite", favorite_tool_path(tool, type: "favorite"), method: :get      %p= link_to "Unfavorite", favorite_tool_path(tool, type: "unfavorite"), method: :get      %p= link_to "Edit", edit_tool_path(tool)      %p= link_to 'http://ocubit.com/tools/'+tool.id.to_s      %p= time_ago_in_words(tool.created_at)  

Thanks for all helpful replies, appreciated!

Rails: Choosing an object on button click and showing info on modal

Posted: 07 Sep 2016 06:23 AM PDT

I have a long list of cats in my database

Cat(id: integer, name: string, gender: integer, home: boolean, created_at: datetime, updated_at: datetime)  

and on my web page I wish to open a Bootstrap modal with the information of only one cat in it. The id of the cat would be determined on button click. In my CatsController I have defined

def index   @cats = Cat.all  end  

and the path /cats/ shows

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"> Open Modal </button>      <div class="modal fade" id="myModal" role="dialog">      <div class="modal-dialog">        <!-- Modal content-->        <div class="modal-content">          <div class="modal-header">            <button type="button" class="close" data-dismiss="modal">&times;</button>            <h4 class="modal-title">Modal Header</h4>          </div>          <div class="modal-body">            <p>Some text in the modal.</p>          </div>          <div class="modal-footer">            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>          </div>        </div>      </div>    </div>  

How can this be done the Rails way?

Ruby on Rails execute recurring task

Posted: 07 Sep 2016 05:54 AM PDT

I need to perform a task roughly every 1 minute on my rails application. So far I have tried delayed job (scheduling a job every minute Rails 3.1 on Heroku) with no success (runs only the one time and then stopped) and right now I'm trying with Sidetiq gem (https://github.com/endofunky/sidetiq).

I have installed the gem and created the file

/config/initializers/sidetiq_test.rb  

here's the code that I put inside:

class MyWorker    include Sidekiq::Worker    include Sidetiq::Schedulable      recurrence { hourly.minute_of_hour(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60) }      def perform      p '####################################'      p 'clients'    end  end  

I will perform some task in the official version but now I just insterted couple of prints. I have restarted the server, no errors but nothing happens, do you know what am I missing?

One last note: the solution must be heroku compatible, because I don't have access to the crontab.

How to pass arguments in I18n.translate

Posted: 07 Sep 2016 05:45 AM PDT

I18n.translate can translate error.messages like this:

I18n.translate('error.messages.taken')  -> has already been taken  

But there are some error messages that contains arguments like:

I18n.translate('error.messages.greater_than_or_equal_to')  -> must be greater than or equal to %{count}"  

Is it possible to pass the argument 'count' in the I18n.translate?

Creating has_one association within the same model

Posted: 07 Sep 2016 05:54 AM PDT

Let us consider the below model.

User{ id:number(primary_key), column1:string, column2:string)  

Now, the column1 can be any string, but column2 can be either null, or have values from column1. However column1 and column2 can't be same. I.E. column2 will be the foreign key and it will reference column1.

How will i create a has_one relationship with these constraints.

Something like,

has_one :master_agreement, :class_name => 'User', :foreign_key => 'column2', :primary_key => 'column1'  

but the above mentioned doesn't work for me.

Could performance issues imerge when using ActionCable in Production?

Posted: 07 Sep 2016 06:24 AM PDT

I'm planning to have a Rails App that has a very content rich interactive page where many users will connect to.

Development has went well and small time testing on the Dev servers went without a hitch either.

Problems started when we started alpha testing with selected groups of people. the sever would grind to a halt suddenly. Nginx would stop because of queue being full. I was at a lose for a while, but after looking around, came to the conclusion that the live actioncable was completely eating up my memory.This especially gets bad when the user reloads the page multiple times that subscribes to actioncable, causing additional process to become active, completely stopping the server, only being cured by a nginx reboot.

I currently run a 2core 1GB memory SSD run VPS server for alpha testing, perhaps at tops 20 concurrent users.Should I be running into performance problems with such load? or should tuning the code or redis, passenger fix this?

I know its hard to say any definitive things without more specifics, but could a ballpark estimate be done with the information?

How set cookie sent from server to a client on a different port

Posted: 07 Sep 2016 05:30 AM PDT

I have a backend server (powered by Rails), whose APIs are used by a HTML5 frontend that runs on a Node simple development server.

Both are on the same host: my machine.

When I login from the frontend to the backend, rails sent me the session cookie. I can see it in the response headers, the problem is that browsers do not save it.

Policies are right, If I serve the same frontend directly from the rails app cookies are set right.

The only difference I can see is that when the frontend run on Node server, It runs on the port 8080 and rails is on the port 3000. I knew that cookies are not supposed to be port specific, so I am missing what is happening here.

Any thoughts? solutions?

(I need to be able to keep the setup this way, so to have the frontend served from Node and the backend on rails on different ports)

Tool for slicing app into microservices

Posted: 07 Sep 2016 05:31 AM PDT

We've refactored our code a bit and I feel that we could separate some parts of our app into microservices. However it would be helpful to use a tool that would show me a graph of references between parts (directories) of our app.

Our app is in Ruby on Rails.

I know that I won't get 100% coverage of coupling between modules since ruby is a dynamic language... any graph would be useful though.

Javascript / jQuery - Price calculation

Posted: 07 Sep 2016 05:59 AM PDT

I'm building an events app using Ruby on Rails. At the moment a user who wishes to book onto an event can only book and pay for one space at a time. I need to offer the facility for them to book multiple spaces and pay the appropriate price - so 5 spaces for £10 each = £50 to pay etc. I've looked for appropriate solutions in RoR to sort this but I'm hitting a brick wall. However, I believe I've perhaps approached this the wrong way and that a solution using javascript or jQuery is the best way forward. I'm very much a novice at both and need some assistance in achieving this objective.

Here's my payment/booking page -

Booking page

I want a User to be able to place the number of spaces in the first text area and for the price (total amount) to change accordingly.

Here's my other relevant code -

bookings_controller.rb

class BookingsController < ApplicationController        before_action :authenticate_user!        def new          # booking form          # I need to find the event that we're making a booking on          @event = Event.find(params[:event_id])          # and because the event "has_many :bookings"          @booking = @event.bookings.new(quantity: params[:quantity])          # which person is booking the event?          @booking.user = current_user          #@booking.quantity = @booking.quantity          @total_amount = @booking.quantity.to_f * @event.price.to_f      end        def create          # actually process the booking          @event = Event.find(params[:event_id])          @booking = @event.bookings.new(booking_params)          @booking.user = current_user          @price = price          @quantity = quantity          #@total_amount = @booking.quantity.to_f * @event.price.to_f            Booking.transaction do                @event.reload              if @event.bookings.count > @event.number_of_spaces              flash[:warning] = "Sorry, this event is fully booked."              raise ActiveRecord::Rollback, "event is fully booked"              end           end            if @booking.save                # CHARGE THE USER WHO'S BOOKED              # #{} == puts a variable into a string              Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",                  card: @booking.stripe_token, description: "Booking number #{@booking.id}")                flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          else              flash[:error] = "Payment unsuccessful"              render "new"          end            if @event.is_free?                @booking.save!              flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          end      end        #def total_amount          #@total_amount = @booking.quantity * @event.price      

No comments:

Post a Comment