Rails Devise flash key is always being set to alert Posted: 27 Mar 2016 06:12 AM PDT I used this link to add flash messages to my rails app. The alerts show up, however the key is not set to success, notice or danger. Instead when I check the class of the flash messages from the browser, it has a class of alert-alert and as a consequence isn't styled properly. Why is devise setting the key to alert, and how can I get the right keys to be sent? Thanks! [UPDATE] The error messages like "password is too short" do show up with the class of alert-danger, but the flash messages like "you have signed in" still don't grab the right key. What am I doing wrong? |
Rails Validations and the DRY principle Posted: 27 Mar 2016 06:34 AM PDT I have 9 different models, all with a column called 'name'. In each model I have the following validation: validates :name, presence: true, uniqueness: true To adhere to the DRY principle, should that validation go in a parent class and have my models that use that validation inherit from the parent class? |
Ruby BigDecimal multiplication Posted: 27 Mar 2016 06:35 AM PDT I'm in trouble with Bigdecimal multiplication. I have a column: t.decimal "average_price", precision: 8, scale: 2 My sample average_price looks like "3.59280368" . When I'm try to make some calculations with this value, I get: @itam.average_price * 1000000 = 3590000 Why not 3592803 ? |
Couldn't pass params to ticket purchase action Posted: 27 Mar 2016 05:11 AM PDT I am building an application where a user can find an event and buy a ticket to that event. Here are my files: tickets/new.html.erb: <%= form_tag('/ticket/finish') do %> <% @event.ticket_types.each do |ticket_type| %> <tr> <td><%= ticket_type.name %></td> <td> <%= number_to_currency(ticket_type.price, unit: 'VND ', precision: 0) %></td> <td> <%= select_tag(:quantity, options_for_select(0..10)) %></td> </tr> <br> <% end %> <p> <%= submit_tag 'Purchase Ticket', class: 'btn btn-primary' %> </p> <% end %> tickets_controller.rb: class TicketsController < ApplicationController def new @event = Event.find(params[:event_id]) @ticket = Ticket.new end def purchase end end event.rb: class Event < ActiveRecord::Base belongs_to :user belongs_to :venue belongs_to :category has_many :ticket_types validates_associated :ticket_types validates_presence_of :user validates_presence_of :name, :extended_html_description, :hero_image_url # validates_presence_of :venue, :category validates_uniqueness_of :name,scope: [:venue_id, :starts_at] def has_ticket_types? !!self.ticket_types.present? end end ticket_types.rb: class TicketType < ActiveRecord::Base belongs_to :event validates_presence_of :name, :price, :max_quantity validates_uniqueness_of :name, scope: :event_id end routes.rb: Rails.application.routes.draw do devise_for :users root 'events#index' get '/yourevents', to: 'events#user_events' resources :events do resources :tickets end post '/ticket/purchase', to: 'tickets#purchase' get 'ticket/finish', to: 'tickets#finish' resources :events do resources :ticket_types end resources :venues end My goal is I want when user click the 'purchase ticket' button, it will lead them to a page that shows them the ticket types, and the quantity of those ticket types they have just bought. However, I have no idea how can I pass those params in my purchase action since I don't have a ticket model. Could anybody here give me some hint or guide me to the right direction? Thank you in advance. |
Rendering tree structures in Rails Slim template Posted: 27 Mar 2016 04:24 AM PDT There are several cases of tree structures in an app I am working on. Currently these have been coded in Ruby helpers (generally just as a bunch of string con-cats and occasional use of other helpers), but Id rather them be coded directly in the relevant views (most are one-off HTML structures), or partials where being reused. But is it possible to render such a recursive structure in Slim (other than recursively invoking a partial for the recursive part, which still splits it into at least 2 files). e.g. a simple tree might be like this: <div id="table-of-contents" class="tree"> <h1>Table of Contents</h1> <ol> <li><a href="/somepage/">1 Header</a> <ol> <li><a href="/somepage/sub">1.1 sub-Header</a> <ol> <li><a href="/sompage/sub#sub">1.1.1 Sub-sub-header</a></li> </ol> </li> <li><a>1.2 sub-Header</a></li> </ol> </li> <li><a>2 Header 2</a></li> <ol> </div> Thinking something like this, but this is not valid syntax -def toc_tree(prefix, items) ol -for item, i in items.each_with_index li a href=item.url ="#{prefix}#{i} #{item.name}" - if item.children? =toc_tree("#{prefix}#{i}.", item.children) div#table-of-contents.tree h1 Table of Contents =toc_tree("", @toc) |
NodeJS + Socket.Io or ActionCable? Posted: 27 Mar 2016 04:11 AM PDT I am trying to create a real-time app right now and I'm tossing up between Rail's newest feature in ver.5 ActionCable and node.js + Socket.io. If I wanted to analyse chat messages in real-time, which framework would you recommend? I heard that mongoDB, node and socket is really quick at storing information but maybe not as robust as rails when it comes to analysis? Would be great to have some additional thoughts! |
RoR string from array Posted: 27 Mar 2016 04:14 AM PDT I have an array of hashes generated by map arr = current_order.order_items.map{|oi|[{name:oi.name,price:oi.price}] [{:name=>"Jacket", :price=>300}, {:name=>"Bag", :price=>650 }, {:name=>"Suit", :price=>300}].to_s i need to make a string from it like this name: Jacket,price:300 name: Bag,price:650 name: Suit,price:300 What i did it gsub every needed element like gsub(':size=>','size:') but it looks very ugly Need more convenient solution for this |
How to model in rails, users login to input days of each month they are available to attend Posted: 27 Mar 2016 03:49 AM PDT Thinking of building a web application to be shared amongst the local volunteer lifeguards. They log in and create a profile with their name, email and phone number. But most importantly update their monthly availability from a page that presents the days of the month in a checkbox fashion. Any clues to get me jump start modelling this in rails. What would be the best approach to tackle the availability table? Regards |
Creating links through nested resource Posted: 27 Mar 2016 03:45 AM PDT I am trying to create a link for a nested resource by iterating through an associated class. <% @category.subcategories.each do |subcat| %> Question: What should be the best way to create links using the code above. And oh, here's what my nested resource looks like. resources :categories do resources :subcategories end Thank you. |
Obtain a Facebook app access token using Koala and Ruby on Rails Posted: 27 Mar 2016 03:12 AM PDT I've been trying to use my RoR app to connect to the Facebook API for a day without any luck. I'm using Ruby on Rails and Koala. If I try to connect as follows: graph = Koala::Facebook::API.new(User_Token) Then there is no problem. (Where user token was obtained from https://developers.facebook.com/tools/access_token/) The problem is that the user token expires. I am aware that there is a way to extend the app User Token, but I would rather not resort to this. Rather, I am trying to authenticate my app to obtain an APP ACCESS TOKEN which I can use in lieu of the User Token (as per https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens. Please note this refers to the App Access Token, not the App Token which was referred to in the first link). In order to obtain the App Access Token, I have followed a tutorial and provided this code in my controller: id = <my app id> secret = <my app secret> callbackUrl = "http://localhost:3000/events/appcallback" @ouath = Koala::Facebook::OAuth.new(id, secret, callbackUrl) redirect_to @oauth.url_for_oauth_code() in my routes.rb I have: match "events/appcallback" => "events#appCalledBack", via: :get This is purely to test that the callback worked. My intention was then to do something like: App_Access_Token = @oauth.get_access_token(params[:code]) But instead I get an error: NoMethodError in EventsController#index undefined method `url_for_oauth_code' for nil:NilClass Please note that I am not interested in obtaining an access token for a user; I want one for my app, so that I can connect to the api a la: graph = Koala::Facebook::API.new(App_Access_Token) Any help would be greatly, greatly appreciated. |
Validates Uniqueness Method to follow only one time Posted: 27 Mar 2016 07:19 AM PDT I create a following system exactly like that with users (Devise). I followed the Ryan Bates Rails casts http://railscasts.com/episodes/163-self-referential-association In this code we can add numerous times the same user, I want to block when people has added as a friend. For example when User1 has added a User2 the link will be block. I give you some codes to understand. The migration is called FriendShip class CreateFriendships < ActiveRecord::Migration def change create_table :friendships do |t| t.integer :user_id t.integer :friend_id t.timestamps null: false end end end The model for users is has_many :friendships has_many :friends, :through => :friendships The model for Friendship is belongs_to :user belongs_to :friend, :class_name => "User" The Friendship controller class FriendshipsController < ApplicationController def create @friendship = current_user.friendships.build(:friend_id => params[:friend_id]) if @friendship.save flash[:notice] = "Added friend." redirect_to current_user else flash[:error] = "Unable to add friend." redirect_to current_user end end def destroy @friendship = current_user.friendships.find(params[:id]) @friendship.destroy flash[:notice] = "Removed friendship." redirect_to current_user end end Thank you for your help |
rails 4 rspec 3 testing before validation Posted: 26 Mar 2016 11:53 PM PDT I am trying to build a spec to make sure duplicate companies are not created. When I used the following spec the company is properly assigned, however the factory still creates 3 companies. This is not the desired behavior. How would I adjust this spec to meet the criteria for the before validation call back? Spec describe 'before validation' do it 'prevents duplicate companies' do company = create(:company) job1 = create(:job, company: company) job2 = create(:job, company: company) binding.pry end end Model class Job < ActiveRecord::Base ... before_validation :find_company ... private ... def find_company existing_company = Company.where(email: company.email) if company self.company = existing_company.first if existing_company.count > 0 end end Factory FactoryGirl.define do factory :job do category company title { FFaker::Company.position } location { "#{FFaker::Address.city}, #{FFaker::AddressUS.state}" } language_list { [FFaker::Lorem.word] } short_description { FFaker::Lorem.sentence } description { FFaker::HTMLIpsum.body } application_process { "Please email #{FFaker::Internet.email} about the position." } end end |
Controller testing with js.erb format Posted: 27 Mar 2016 01:33 AM PDT I'm using Rails 4.2.5, I've written a controller test for the destroy action, an I'm using ajax call to destroy and using destroy.js.erb file. Please help me to solve the following issue to pass the test when it calls js format, I'm pasting error below. def destroy @status = @song.destroy respond_to do |format| format.js end end SongsControllerTest#test_should_destroy_song: ActionController::UnknownFormat: ActionController::UnknownFormat app/controllers/songs_controller.rb:36:in `destroy' songs_controller_test.rb test "should destroy song" do assert_difference('Song.count', -1) do delete :destroy, id: @song end get :destroy, format: 'js' end destroy.js.erb var element = document.getElementById("<%="song#{@song.id}" %>"); <%if @status%> element.parentNode.parentNode.remove(); <%end%> |
Heroku not sending email with Gmail SMTP Posted: 27 Mar 2016 12:10 AM PDT The app works everything, I'm trying to use Confirmable with Devise, on my Rails app it says that the email was sent, but I never receive it. I'm configuring it with Gmail though SMTP. Thanks. the Heroku log: 2016-03-27T04:49:23.448947+00:00 app[web.1]: Rendered devise/shared/_links.html.erb (1.0ms) 2016-03-27T04:49:23.449047+00:00 app[web.1]: Rendered devise/sessions/new.html.erb within layouts/application (9.4ms) 2016-03-27T04:49:23.450618+00:00 app[web.1]: Rendered layouts/_navbar.html.erb (0.5ms) 2016-03-27T04:49:23.451085+00:00 app[web.1]: Rendered layouts/_footer.html.erb (0.1ms) 2016-03-27T04:49:23.451438+00:00 app[web.1]: Completed 200 OK in 14ms (Views: 12.2ms | ActiveRecord: 0.0ms) 2016-03-27T04:49:23.949248+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=my-task-tracker.herokuapp.com request_id=146e1632-c484-471f-97c3-feaaf1a1b2ed fwd="108.219.46.125" dyno=web.1 connect=3ms service=11ms status=304 bytes=133 2016-03-27T04:49:29.128082+00:00 heroku[router]: at=info method=GET path="/users/confirmation/new" host=my-task-tracker.herokuapp.com request_id=1b9d8a7c-7c9e-4e50-a4f0-4be476c92dfb fwd="108.219.46.125" dyno=web.1 connect=1ms service=33ms status=200 bytes=3182 2016-03-27T04:49:29.132299+00:00 app[web.1]: Started GET "/users/confirmation/new" for 108.219.46.125 at 2016-03-27 04:49:29 +0000 2016-03-27T04:49:29.137153+00:00 app[web.1]: Processing by Devise::ConfirmationsController#new as HTML 2016-03-27T04:49:29.151819+00:00 app[web.1]: Rendered devise/shared/_links.html.erb (1.4ms) 2016-03-27T04:49:29.151898+00:00 app[web.1]: Rendered devise/confirmations/new.html.erb within layouts/application (6.7ms) 2016-03-27T04:49:29.153383+00:00 app[web.1]: Rendered layouts/_navbar.html.erb (0.5ms) 2016-03-27T04:49:29.153706+00:00 app[web.1]: Rendered layouts/_footer.html.erb (0.1ms) 2016-03-27T04:49:29.154027+00:00 app[web.1]: Completed 200 OK in 17ms (Views: 15.5ms | ActiveRecord: 0.0ms) 2016-03-27T04:49:29.386263+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=my-task-tracker.herokuapp.com request_id=c0dbab1b-9032-4787-bb64-3070feb0066b fwd="108.219.46.125" dyno=web.1 connect=1ms service=7ms status=304 bytes=133 2016-03-27T04:49:32.066230+00:00 app[web.1]: Started POST "/users/confirmation" for 108.219.46.125 at 2016-03-27 04:49:32 +0000 2016-03-27T04:49:32.068692+00:00 app[web.1]: Processing by Devise::ConfirmationsController#create as HTML 2016-03-27T04:49:32.068831+00:00 app[web.1]: Parameters: {"utf8"=>"✓", "authenticity_token"=>"HnARWykNdBAKSmewO6IZaOQ4Vokg9V46SxzCUADvtybFpbVVfuErGn/QLRQXWc4j79Krq9sAfBveAjR1ar9C7g==", "user"=>{"email"=>"smith.hampton23@gmail.com"}, "commit"=>"Resend confirmation instructions"} 2016-03-27T04:49:32.082510+00:00 app[web.1]: User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."unconfirmed_email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["unconfirmed_email", "smith.hampton23@gmail.com"]] 2016-03-27T04:49:32.091027+00:00 app[web.1]: User Load (3.1ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["email", "smith.hampton23@gmail.com"]] 2016-03-27T04:49:32.103821+00:00 app[web.1]: (12.0ms) BEGIN 2016-03-27T04:49:32.126821+00:00 app[web.1]: (20.9ms) COMMIT 2016-03-27T04:49:32.227009+00:00 app[web.1]: Rendered devise/mailer/confirmation_instructions.html.erb (8.6ms) 2016-03-27T04:49:32.973627+00:00 app[web.1]: 2016-03-27T04:49:32.973641+00:00 app[web.1]: Devise::Mailer#confirmation_instructions: processed outbound mail in 843.7ms 2016-03-27T04:49:33.194388+00:00 app[web.1]: 2016-03-27T04:49:33.194402+00:00 app[web.1]: Sent mail to smith.hampton23@gmail.com (220.6ms) 2016-03-27T04:49:33.194407+00:00 app[web.1]: Date: Sun, 27 Mar 2016 04:49:32 +0000 2016-03-27T04:49:33.194408+00:00 app[web.1]: From: smith.hampton23@gmail.com 2016-03-27T04:49:33.194409+00:00 app[web.1]: Reply-To: smith.hampton23@gmail.com 2016-03-27T04:49:33.194410+00:00 app[web.1]: To: smith.hampton23@gmail.com 2016-03-27T04:49:33.194413+00:00 app[web.1]: Message-ID: <56f7665cef03b_33febb8de74141bf@29f38684-21c7-41d6-821e-42ae72d533ac.mail> 2016-03-27T04:49:33.194414+00:00 app[web.1]: Subject: Confirmation instructions 2016-03-27T04:49:33.194415+00:00 app[web.1]: Mime-Version: 1.0 2016-03-27T04:49:33.194415+00:00 app[web.1]: Content-Type: text/html; 2016-03-27T04:49:33.194416+00:00 app[web.1]: charset=UTF-8 2016-03-27T04:49:33.194417+00:00 app[web.1]: Content-Transfer-Encoding: 7bit 2016-03-27T04:49:33.194418+00:00 app[web.1]: <p>Welcome smith.hampton23@gmail.com!</p> 2016-03-27T04:49:33.194417+00:00 app[web.1]: 2016-03-27T04:49:33.194419+00:00 app[web.1]: 2016-03-27T04:49:33.194420+00:00 app[web.1]: <p>You can confirm your account email through the link below:</p> 2016-03-27T04:49:33.194421+00:00 app[web.1]: 2016-03-27T04:49:33.194423+00:00 app[web.1]: <p><a href="https://my-task-tracker.herokuapp.com/users/confirmation?confirmation_token=yBnGnJEZkkaL-pU7_Y_U&locale=en">Confirm my account</a></p> 2016-03-27T04:49:33.194424+00:00 app[web.1]: 2016-03-27T04:49:33.201842+00:00 app[web.1]: Redirected to https://my-task-tracker.herokuapp.com/users/sign_in 2016-03-27T04:49:33.202005+00:00 app[web.1]: Completed 302 Found in 1133ms (ActiveRecord: 37.8ms) 2016-03-27T04:49:33.187258+00:00 heroku[router]: at=info method=POST path="/users/confirmation" host=my-task-tracker.herokuapp.com request_id=3fa250b9-23e4-43f7-8e10-4f37e54d9a79 fwd="108.219.46.125" dyno=web.1 connect=1ms service=1162ms status=302 bytes=1245 2016-03-27T04:49:33.361655+00:00 app[web.1]: Started GET "/users/sign_in" for 108.219.46.125 at 2016-03-27 04:49:33 +0000 2016-03-27T04:49:33.372833+00:00 app[web.1]: Processing by Devise::SessionsController#new as HTML 2016-03-27T04:49:33.400388+00:00 app[web.1]: Rendered devise/shared/_links.html.erb (1.3ms) 2016-03-27T04:49:33.400564+00:00 app[web.1]: Rendered devise/sessions/new.html.erb within layouts/application (24.7ms) 2016-03-27T04:49:33.402011+00:00 app[web.1]: Rendered layouts/_navbar.html.erb (0.6ms) 2016-03-27T04:49:33.402772+00:00 app[web.1]: Rendered layouts/_footer.html.erb (0.1ms) 2016-03-27T04:49:33.403290+00:00 app[web.1]: Completed 200 OK in 30ms (Views: 28.3ms | ActiveRecord: 0.0ms) 2016-03-27T04:49:33.376910+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=my-task-tracker.herokuapp.com request_id=72189b98-69bc-415f-ade7-a21856684a0a fwd="108.219.46.125" dyno=web.1 connect=5ms service=47ms status=200 bytes=4220 2016-03-27T05:23:51.692897+00:00 heroku[web.1]: Idling 2016-03-27T05:23:51.693798+00:00 heroku[web.1]: State changed from up to down 2016-03-27T05:23:57.760741+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2016-03-27T05:23:59.284360+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:174:in `select' 2016-03-27T05:23:59.284343+00:00 app[web.1]: [2016-03-27 05:23:59] FATAL SignalException: SIGTERM 2016-03-27T05:23:59.284363+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:174:in `block in start' 2016-03-27T05:23:59.284364+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:32:in `start' 2016-03-27T05:23:59.284365+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:162:in `start' 2016-03-27T05:23:59.284365+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:34:in `run' 2016-03-27T05:23:59.284367+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands/server.rb:80:in `start' 2016-03-27T05:23:59.284366+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:286:in `start' 2016-03-27T05:23:59.284367+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:80:in `block in server' 2016-03-27T05:23:59.284368+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `tap' 2016-03-27T05:23:59.284369+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!' 2016-03-27T05:23:59.284369+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `server' 2016-03-27T05:23:59.284370+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>' 2016-03-27T05:23:59.284390+00:00 app[web.1]: bin/rails:9:in `require' 2016-03-27T05:23:59.284391+00:00 app[web.1]: bin/rails:9:in `<main>' 2016-03-27T05:23:59.284464+00:00 app[web.1]: [2016-03-27 05:23:59] INFO going to shutdown ... 2016-03-27T05:23:59.284516+00:00 app[web.1]: [2016-03-27 05:23:59] INFO WEBrick::HTTPServer#start done. 2016-03-27T05:23:59.284544+00:00 app[web.1]: Exiting 2016-03-27T05:24:00.235601+00:00 heroku[web.1]: Process exited with status 143 2016-03-27T05:29:00.462487+00:00 heroku[web.1]: Unidling 2016-03-27T05:29:00.462791+00:00 heroku[web.1]: State changed from down to starting 2016-03-27T05:29:03.166146+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 18537 -e production` 2016-03-27T05:29:06.739510+00:00 app[web.1]: [2016-03-27 05:29:06] INFO WEBrick 1.3.1 2016-03-27T05:29:06.739563+00:00 app[web.1]: [2016-03-27 05:29:06] INFO ruby 2.2.4 (2015-12-16) [x86_64-linux] 2016-03-27T05:29:06.739784+00:00 app[web.1]: [2016-03-27 05:29:06] INFO WEBrick::HTTPServer#start: pid=3 port=18537 2016-03-27T05:29:07.331731+00:00 heroku[web.1]: State changed from starting to up 2016-03-27T05:29:08.588190+00:00 heroku[router]: at=info method=GET path="/" host=my-task-tracker.herokuapp.com request_id=4343eecf-3333-496c-936d-9881c5d12412 fwd="108.219.46.125" dyno=web.1 connect=0ms service=92ms status=302 bytes=1122 2016-03-27T05:29:08.517272+00:00 app[web.1]: => Booting WEBrick 2016-03-27T05:29:08.517309+00:00 app[web.1]: => Rails 4.2.4 application starting in production on http://0.0.0.0:18537 2016-03-27T05:29:08.517311+00:00 app[web.1]: => Run `rails server -h` for more startup options 2016-03-27T05:29:08.517312+00:00 app[web.1]: => Ctrl-C to shutdown server 2016-03-27T05:29:08.517313+00:00 app[web.1]: Started GET "/" for 108.219.46.125 at 2016-03-27 05:29:08 +0000 2016-03-27T05:29:08.555988+00:00 app[web.1]: Processing by PagesController#index as HTML 2016-03-27T05:29:08.565676+00:00 app[web.1]: Completed 401 Unauthorized in 10ms (ActiveRecord: 0.0ms) 2016-03-27T05:29:08.953091+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=my-task-tracker.herokuapp.com request_id=69e03185-2d8f-41c5-ba23-d62fe66fdf6e fwd="108.219.46.125" dyno=web.1 connect=0ms service=57ms status=200 bytes=4002 2016-03-27T05:29:08.917010+00:00 app[web.1]: Started GET "/users/sign_in" for 108.219.46.125 at 2016-03-27 05:29:08 +0000 2016-03-27T05:29:08.919553+00:00 app[web.1]: Processing by Devise::SessionsController#new as HTML 2016-03-27T05:29:08.961087+00:00 app[web.1]: Rendered devise/shared/_links.html.erb (2.9ms) 2016-03-27T05:29:08.961219+00:00 app[web.1]: Rendered devise/sessions/new.html.erb within layouts/application (10.0ms) 2016-03-27T05:29:08.964675+00:00 app[web.1]: Rendered layouts/_navbar.html.erb (1.4ms) 2016-03-27T05:29:08.965909+00:00 app[web.1]: Rendered layouts/_footer.html.erb (0.3ms) 2016-03-27T05:29:08.966140+00:00 app[web.1]: Completed 200 OK in 47ms (Views: 18.3ms | ActiveRecord: 5.9ms) 2016-03-27T05:29:09.845722+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=my-task-tracker.herokuapp.com request_id=5893b11b-579b-4937-9dc7-1b4b63c7ea3f fwd="108.219.46.125" dyno=web.1 connect=0ms service=4ms status=304 bytes=133 env/production.rb config.action_mailer.default_url_options = { :host => 'https://my-task- tracker.herokuapp.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = false config.action_mailer.default :charset => "utf-8" config.action_mailer.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :user_name => ENV["GMAIL_USERNAME"], :password => ENV["GMAIL_PASSWORD"], :authentication => "plain", :enable_starttls_auto => true } |
Using a Controller Method with Resque Background Job Posted: 26 Mar 2016 10:49 PM PDT I am on Rails 4 using Resque w/ Redis. My question: How can I use a controller method, which is currently defined in my application_controller, inside of my background job? Here is the current method I have defined: def push_to_google(token, message) if token.present? gcm = GCM.new("843jf9384fj839f848j890fj3") registration_ids = ["#{token}"] # an array of one or more client registration tokens options = {data: {notification: "#{message}"}} response = gcm.send(registration_ids, options) end end which I would like to use in this background job defined in my delayed_notifications: class DelayedNotifications @queue = :notifications_queue def self.perform(registration_id, user_name) push_to_google(registration_id, "New message from #{user_name}.") end end Of course, my jobs are currently failing with this error: undefined method 'push_to_google' for DelayedNotifications:Class Thanks for the help in advance. |
Rails Active Record Seems to Be Broken, Rails 4.0.2 Posted: 26 Mar 2016 10:34 PM PDT O.k. this is driving me crazy - if anyone could help that would be great. I have a simple table "threads" with an auto id and a "name" field with one record (id = 1, name = "space"). I have a model named "Thread.rb". class Thread < ActiveRecord::Base end I have a controller that calls: @thread = Thread.find_by_id(1) But when loading a page I get the following error in the controller: undefined method `find_by_id' for Thread:Class I've used find_by_sql numerous times in the same project with no problem, but when using the simple activerecord accessors rails errors out on "find", "find_by_id" etc. I'm on rails 4.0.2 |
Rails Engine: Create dummy model for relations? Posted: 26 Mar 2016 10:42 PM PDT I am trying to make a Rails Engine that can be plugged into my applications and manage friendships between users. To do that, all the logic dealing with friend requests, acceptance, etc, is going to live in a Rails Engine. When I create my Friendship model, it needs a belongs_to relation for two Users (two friends). But, I don't want to tie a user to this engine. I want this engine to work generically with any User an application has established. What technique does one use to create a dummy User that is never to be included in the host application? (I want to avoid a migration of the engine pulling in this dummy User .) Update: I removed the second question, pertaining to how to then override the engine's User with the host app's User . I found the answer to that in the guides (http://edgeguides.rubyonrails.org/engines.html#configuring-an-engine). |
Partial Rendered in index.html.erb Won't Display in show.html.erb Posted: 26 Mar 2016 10:39 PM PDT A beginner here, so, please bear with me. :) I have a partial in a partial that's displaying correctly in my views > products > index.html.erb : <div> <table> ... <tbody> <%= render product %> </tbody> ... </table> </div> This is the _product partial: <div> <td> <%= render "product_row", product: product, order_item: @order_item %> </td> </div> ..which points to this _product_row partial: <div> <%= form_for order_item, remote: true do |f| %> <%= number_to_currency product.price %> <%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %> <%= f.hidden_field :product_id, value: product.id %> <%= f.submit %> <% end %> </div> All is well, BUT I want to display _product_row in my views > products > show.html.erb instead. So, I copy and paste it and get this error: NameError in Products#show undefined local variable or method `product' for #<#<Class:...> Extracted source: <%= render "product_row", product: product, order_item: @order_item %> ...so I go in my products_controller and put this: def show @product = Product.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @product } end end 'still the same error. Any help will be appreciated. Thanks! |
rspec model test on string match regex adjustment Posted: 26 Mar 2016 09:08 PM PDT I have the following test in rspec it 'passes regex rules' do job = create(:job) job.valid? expect(job.title).to match(/\A[\w\d .,:-@]+\z/) end This regex pattern matches the model pattern. What is the recommended way to test to make sure this pattern does not change in the model from future developers? Basically I want to test for conditions that do not fall in the approved: can only have 0-9, A-Z, periods, colons, hypens, underscores, and spaces. No new lines (enter keys) Update Based on Generate random string based on Regex? I decided to go with (0..255).map(&:chr).select{|x| x != /\A[\w\d .,:-@]+\z/}.sample(5).join for now which appears to work, thoughts? |
Ruby on Rails, get children of parent in template Posted: 26 Mar 2016 10:47 PM PDT I'm attempting to build a menu creator with dropdowns, I have everything working except getting the children of the dropdown menus. In my ApplicationController def set_links @alllinks = Link.all end link.rb class Link < ActiveRecord::Base has_many :children, class_name: "Link", foreign_key: "parent_id" belongs_to :parent, class_name: "Link" end And the layout <% @alllinks.each do |link| %> <% if link.dropdown == true %> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><%= link.text %> <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="<%= link.url %>"><%= link.text %></a></li> </ul> </li> <% else %> <% if link.dropdown == false && link.parent == nil %> <li><a href="<%= link.url %>" target="<%= link.target %>"><%= link.text %></a></li> <% end %> <% end %> <% end %> I've attempted to search around but nothing that I could find was of any help. |
Rails Enum on Relationship Model cannot be called from separate controller? Posted: 26 Mar 2016 09:56 PM PDT I have a Relationship model in which i establish a following relationship between users and projects. In this relationship model i use enum to distinguish the type of relationship the user has with the project (basically establishing a "role"). Now in my Projects Controller I am trying to call the projectadmins action def projectadmins @title = "Project Admins" @project = Project.find(params[:id]) authorize @project, :visit? @projects = @project.followers render 'show_projectadmin_project' rescue Pundit::NotAuthorizedError flash[:danger] = "You are not authorized to access this page." redirect_to projects_path || root_path end My Relationships model is: class Relationship < ActiveRecord::Base belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "Project" validates :follower_id, presence: true validates :followed_id, presence: true enum role: [:admin, :collaborator, :visitor] end User & Projects Models: class User < ActiveRecord::Base has_many :own_projects, :class_name=>'Project' has_many :projects has_many :relationships, foreign_key: "follower_id", dependent: :destroy has_many :followed_projects, through: :relationships, source: :followed end class Project < ActiveRecord::Base belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User' has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy has_many :followers, through: :reverse_relationships, source: :follower end 'show_projectadmin_project' view: <h3>Project Administrators</h3> <% if @project.projectadmins.any? %> <% @project.projectadmins.each do |user| %> <div class="no-pad col-md-3"> <div class="inner-border"> <h5><%= link_to user.email, user %></h5> </div> </div> <% end %> <% end %> As is, my code in the controller method is setup to return all following relationships ("@projects = @project.followers")...my question is how can i change this line of code to return all following relationships that have an enum role type of :admin? I assume something like "@projects = @project.followers where (etc, etc)" but I can't seem to find anything that has worked for me. |
Feature test failing when trying to use "check" Posted: 26 Mar 2016 08:29 PM PDT I'm new to feature tests and capybara, I have a real simple feature test right now and I can't get it to pass but I believe it's because of something I'm doing wrong writing the test. I'll post my test and let me know if anything jumps out at anyone and is a clear dev error. I think it's something I'm doing with the check? require "rails_helper" RSpec.feature "Send a message" do scenario "Staff can send a message" do visit "/" group = Group.create!(name: "Group A") user = User.create!(email: "staff@example.com", password: "password") fill_in "Email", with: "staff@example.com" fill_in "Password", with: "password" click_button "Sign in" fill_in "Enter a Message:", with: "Test Message" check("message_group_#{group.id}") click_button "Send Message" expect(page).to have_content("Messages on their way!") end This is the error message I get. Send a message Staff can send a message Failure/Error: expect(page).to have_content("Messages on their way!") expected to find text "Messages on their way!" in "Tulip Time Text Numbers Sent Messages Scheduled Messages Statistics staff@example.com Logout SMS Notifications Use this form to send SMS notifications to Visitors, Staff or Volunteers. Enter a Message: Groups: Group A Scheduled Text Message:" |
Rails Background Job for Creating Records? Posted: 26 Mar 2016 08:31 PM PDT Currently on Rails 4 with Resque. My question is, would it make sense to use a background job for creating a record? Something like... def create @article = Article.new(articles_params) if @article.valid? background_job_here else render 'new' end end The only other documentation I can find on this matter says that it does not make sense to do this, however, does not explain why. Reading Heroku documentation, they suggest that any request taking more than 500 ms be moved off into the background. Creating an article on my site is no exception as it can take upwards of 1,000 ms. If not a background job, how should I architect this? Thx! |
Rails 4 - heroku production issues Posted: 26 Mar 2016 06:06 PM PDT I am having a million problems in trying to deploy my production version with heroku. Js files aren't working, images aren't loading. It's driving me crazy. I've read several posts about different ways of precompiling assets and I have tried all of them. Taking this one step at at a time. What can I do to change this path, so that it gets rendered in production (works fine in development) <%= image_path "cropdust.jpg" %> |
Searchkick rails geospatial search not working Posted: 26 Mar 2016 05:37 PM PDT I'm trying Searchkick on a small Rails app to perform geospatial searches, but I can't get it to work. I have a Venue model: class Venue < ActiveRecord::Base has_and_belongs_to_many :categories searchkick locations: ["location"] def search_data attributes.merge location: [latitude, longitude] attributes.merge categories_title: categories.map(&:name) end end I have added data to my database, and I have run Venue.reindex too. In my controller I'm trying to search by running: term = "london" res = Geocoder.search(term) @location = res.first.geometry['location'] # lat / lng @venues = Venue.search '*', where: { location: { near: [@location['lat'],@location['lng']], within: '2km' } } Although I have valid data in my database, I always get an empty result. Looking at rails console, the query executed against elasticsearch is: { "query":{ "filtered":{ "query":{ "match_all":{ } }, "filter":{ "and":[ { "geo_distance":{ "location":[ -0.08077990000000002, 51.5037119 ], "distance":"2km" } } ] } } }, "size":1000, "from":0, "sort":{ "_geo_distance":{ "location":"51.5037119,-0.08077990000000002" } }, "fields":[ ] } Any ideas? Thanks |
Implementing PJAX - Configuring Server Posted: 26 Mar 2016 05:31 PM PDT My first question here. I searched thoroughly, and unfortunately, I am unable to find an explanation I can understand. I am interested in understanding how PJAX works (link below), so that I can consider implementing it. It seems simple enough, but the requirement to configure the server to recognize PJAX requests has me stumped. I am a front-end developer that is completely unfamiliar with back-end development. For example, how do I configure the server? The PJAX author gives an example in RAILS, so it is a matter of placing that code wherever it goes? I build custom and implement Wordpress, and I use a Wordpress hosting solution. Does that affect where I would configure the server? I know these are general questions, which demonstrate how little I know. I would appreciate if someone could explain the concept of configuring the server and perhaps provide an example of what that would look like. I appreciate your help. https://github.com/defunkt/jquery-pjax |
Heroku deployment not giving basic functions Posted: 26 Mar 2016 05:43 PM PDT I have just migrated to postgresql and pushed to heroku with my first web application. However, it seems the basic contact_us gem doesn't work. Does it just take a while to work or is it a problem with the way I've deployed things? |
Rails c sql command is rollingback instead of updating Posted: 26 Mar 2016 06:02 PM PDT so I tried to run rails c of this: Borrower.update(1, :raised=> 0) and this: Borrower.update(1, raised: 0)
and I get a roll back with this: Borrower Load (0.3ms) SELECT "borrowers".* FROM "borrowers" WHERE "borrowers"."id" = $1 LIMIT 1 [["id", 1]] (0.2ms) BEGIN Borrower Exists (0.5ms) SELECT 1 AS one FROM "borrowers" WHERE (LOWER("borrowers"."email") = LOWER('j@kay.com') AND "borrowers"."id" != 1) LIMIT 1 (0.2ms) ROLLBACK "table with raised = 0" 1 row in set
This is my model for "Borrower": class Borrower < ActiveRecord::Base has_many :lenders has_many :histories, dependent: :destroy has_many :borrowed_from, through: :histories, source: :lender EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :first_name, :last_name, :email, :purpose, :description, :money, presence: true validates :email, uniqueness: {case_sensitive: false}, format: {with: EMAIL_REGEX} has_secure_password end
and my Schema: create_table "borrowers", force: :cascade do |t| t.string "first_name" t.string "last_name" t.string "email" t.string "password_digest" t.integer "money" t.string "purpose" t.text "description" t.integer "raised" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
How do I permanently update the "raised"? |
Show and update nested attributes in rails form Posted: 27 Mar 2016 02:27 AM PDT I have an :item model with nested attributes from :item_galleries showcasing multiple images. I'm able to create an item with the nested images but having issues with editing. I want to be able to show each image attached to the item and able to edit each one. Who ever helps me gets a VIRTUAL COOKIE OR PIE! For the "Item Form View": <%= f.fields_for :item_galleries do |p| %> <%= p.label :image %> <%= link_to "Edit Attachment", edit_item_gallery_path(p) %> <%= p.file_field :image, :multiple => true, name: "item_galleries[image][]" %> <% end %> I'd like to show the image right next to the edit attachment link. This is the edit function in the items_controller: def edit @item = Item.find(params[:id]) @item_galleries = @item.item_galleries.all end def update respond_to do |format| if @item.update(item_params) format.html { redirect_to @item, notice: 'Item was successfully updated.' } else format.html { render :edit } end end end Currently the link that edit_item_galleries_path(p) brings me to is "http://localhost:3000/item_galleries/%23%3CActionView::Helpers::FormBuilder:0x007ffce80b2358%3E/edit" |
How to increment a value with using link_to_add in Rails Posted: 26 Mar 2016 09:47 PM PDT What I'd like to do is to display the value index + 1 when clicked link_to_add ("Add day" button). edit.html.erb <div class="row"> <div class="col-md-12"> <%= simple_nested_form_for(@schedule) do |f| %> <%= render 'schedule_form', f: f %> <%= f.link_to_add "Add day", :rooms, data: {target: '#room'}, class: "btn btn-primary" %> <%= f.submit "Edit my schedule", class: "btn btn-primary" %> <% end %> </div> </div> _schedule_form_html.erb <%= f.label :title %> <%= f.text_field :title, class: 'form-control' %> <div id="room"> <%= f.simple_fields_for :rooms do |a| %> <p><b>Day <%= a.index.to_i + 1 %></b></p> <%= a.input :room %> <% end %> </div> When I clicked link_to_add , Day 1 is always displayed. Is it possible to increment index when I click link_to_add ? Or it would be appreciated if you could give me another solutions. |
No comments:
Post a Comment