Getting dynamic active li for one page bootstrap website Posted: 01 Sep 2016 07:31 AM PDT I want to have dynamic attribute active for li on a current page. I saw this topic:How to get Twitter-Bootstrap navigation to show active link?, but solutions not working for me. I don't have specific controllers for partials views. Method current_page doesn't work with href . I don't use defined routes, that's why don't have link_to . I tried to use data-toggle="pills", correctly marks on navbar current clicked a link, but not reference(not changed view). li a.waves-effect.waves-light href="#{root_path}#slider" Home li a.waves-effect.waves-light href="#{root_path}#about" About us li a.waves-effect.waves-light href="#{root_path}#price" Price li a.waves-effect.waves-light href="#{root_path}#contact" Contact |
'Must contain specific value' on ActiveAdmin field Posted: 01 Sep 2016 07:18 AM PDT I want to test my models on ActiveAdmin by creating them manually. On one of my model, a field says 'Must contain specific value' whatever i write in it. This attribute can only contain a value from a list which is predefined. I suppose this field should not be a text field but a combobox filed with the values of this list. I looked for it on Google but can't find the answer.what I have tried upto is bellow f.input :modele, :as => :select, :collection => proc{current_route.modele.all} but it doesn't work and worse I don't understand what I'm doing. |
Rails: Form with custom button for update Posted: 01 Sep 2016 07:07 AM PDT I have an app for booking shifts. When you book you should be able to add a short comment (string) and then press the book button. I have the available shifts in a table, and want to have a text field like in a form, and add the (optional) text to the shift when you press the book-button. This is what I have so far, when you book a shift, it shows correctly as booked, but the comment doesn't is not added (is nil). Is there a smarter way to add a comment to a shift from the index view? Or how can I modify my code to work? Index: <% if shift.booked? && ( @booker == current_member || current_member.admin?) %> <td><%= link_to 'Avboka', un_book_shift_path(shift), method: :patch %></td> <% elsif shift.booked? && @booker != current_member %> <td></td> <% elsif shift.booked? %> <td><%= shift.comment %></td> <% elsif (!shift.booked? && prev_lshift.booked? ) || index == 0 %> <td><%= form_for shift, :url => book_shift_path(shift) do |f| %> <%= f.label :comment, 'Kommentar' %> <%= f.text_field :comment %> <%= f.submit "Boka" %> </td> <% end %> <% else %> <td></td> <% end %> shift controller: def book @shift = Shift.find(params[:id]) @shift.update_attributes(shift_params) member = Member.find(current_id) if SubShift.find_by(booked_by: current_id) == nil flash[:danger] = "danger" redirect_to shifts_url elsif @shift.overlaps?(@shift, current_id) flash[:danger] = "Danger" redirect_to shifts_url else @shift.book(current_id) redirect_to shifts_url end end shift model def book(current_id) self.update(booked:true, booked_by:current_id) end |
Testing aasm state transitions with rspec Posted: 01 Sep 2016 07:06 AM PDT I'm using aasm gem to handle state transitions in my project. I have a simple model that looks like this: class TransferPostingBid < ActiveRecord::Base include AASM aasm :status do state :offered, initial: true state :wait_for_pap_confirmation state :confirmed_by_pap state :retracted_by_pap event :pap_choosed do transitions from: :offered, to: :wait_for_pap_confirmation end event :confirmed_by_pap do transitions from: :wait_for_pap_confirmation, to: :confirmed_by_pap end event :retracted_by_pap do transitions from: :wait_for_pap_confirmation, to: :retracted_by_pap end end end And I'm trying to test transitions with aasm built in rspec matchers: require 'rails_helper' describe TransferPostingBid, type: :model do describe 'state transitions' do let(:transfer_posting_bid) { TransferPostingBid.new } it 'has default state' do expect(transfer_posting_bid).to transition_from(:offered).to(:wait_for_pap_confirmation).on_event(:pap_choosed) end end end When I run this spec it returns me following error: AASM::UnknownStateMachineError: There is no state machine with the name 'default' defined in TransferPostingBid! How can I fix this? |
Generate PDF with embedded video and manipulate objects Posted: 01 Sep 2016 07:02 AM PDT I'm using RoR to generate a PDF with embedded video, for which I use LaTeX with the media9 library. It generates PDFs correctly with embedded media (MP4, MOV, Youtube/Vimeo, etc...). I need to restyle the PDF layout in such a difficult way that doing it with LaTeX it's almost impossible. So I wanted to migrate to Prawn or other Ruby gem that's capable of creating nice-looking PDFs... but no embedded video support. So... Question: Is there a way that I can generate a PDF with the videos (LaTeX), a PDF with the "cool" layout (Prawn or other), and then I can "slice-merge" them in some way? Maybe extracting the raw PDF objects and merging them into the layout PDF? BTW, I've tested pasting the pages, but all of the PDF mergers I've tested break the media objects. Option B: find another Ruby gem that allows you to embed video media into a PDF. Thanks you all. |
Turbolinks and 3d party plugins issue? Posted: 01 Sep 2016 07:00 AM PDT I have website http://www.optimapo.ru/ and I have some 3d party scripts installed: live chat (https://www.jivochat.com/) and yandex analitics. But because of turbolinks they don't work properly. For example live chat appears only on main page. But when we go to another page which is loaded using turbolinks it dissapears. I include scripts in my code before closing body tag <!-- BEGIN JIVOSITE CODE {literal} --> <script type='text/javascript'> (function(){ var widget_id = '2qq06akKwZ';var d=document;var w=window;function l(){ var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '//code.jivosite.com/script/widget/'+widget_id; var ss = document.getElementsByTagName('script')[0]; ss.parentNode.insertBefore(s, ss);}if(d.readyState=='complete'){l();}else{if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})();</script> <!-- {/literal} END JIVOSITE CODE --> <!-- Yandex.Metrika counter --> <script type="text/javascript"> (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter39034390 = new Ya.Metrika({ id:39034390, clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true, trackHash:true, ut:"noindex" }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/39034390?ut=noindex" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter --> </body> So what do I do to make scripts work with turbolinks? |
Capistrano deploy fails for repo that was moved from github to private git.. stil trying to contact github.. why? Posted: 01 Sep 2016 06:21 AM PDT I have a Rails 4 project that started at github and then it was moved to a private git repository. I can work perfectly with the repo (push, clone). I searched for references to the github repo somewhere in the code but none exists.. it must be something related to GIT and how the repository started.. Important: I was able to deploy with this configuration from my private repo until I removed the github one. Of course I have updated config/deploy.rb set :repo_url, '/srv/git/project.git' Running "git remote -v": origin git@git.server:/srv/git/project.git (fetch) origin git@git.server:/srv/git/project.git (push) Log of capistrano run "bundle exec cap production deploy": 00:00 git:wrapper 01 mkdir -p /tmp server's password: ✔ 01 server 6.019s 00:07 git:check 01 git ls-remote --heads /srv/git/project.git 01 6b0c9f5ad2d8e768902c5da1509fd99915068295 refs/heads/master ✔ 01 server 0.356s 00:07 deploy:check:directories 01 mkdir -p /home/user/applications/project/shared /home/user/applications/project/releases ✔ 01 user@server 0.335s 00:08 deploy:check:linked_dirs 01 mkdir -p /home/user/applications/project/shared/public/assets ✔ 01 user@server 0.331s 00:09 git:clone The repository mirror is at /home/user/applications/project/repo 00:10 git:update 01 git remote update --prune 01 Fetching origin 01 remote: Invalid username or password. 01 fatal: Authentication failed for 'https://github.com/user/project.git/' 01 error: Could not fetch origin Moved from SVN to GIT not so much ago and a bit confused about this behaviour.. any help apreciated! |
Rational behind having parent id of nested resources in RESTful URL Posted: 01 Sep 2016 06:50 AM PDT Given the following URL design for a nested resources in a RESTful API: /magazines/:magazine_id/ads/:id POST What's the rational behind having the magazine id in there given that the ads id uniquiely identifies ads across magazines? Besides that it looks maybe nicer when presenting the user with that URL or simply convention. Is there any deeper meaning or constraint? |
How to deploy the Backbone.js front end part of app to Heroku? Posted: 01 Sep 2016 06:17 AM PDT The project, which I am working on, is divided into back end (Ruby on Rails) and front end (Backbone.js) parts. Currently, we are trying to deploy both parts on Heroku, using separated repositories. We had no problems with back end part, but we found out that our front end is not working, getting internal server error 500. We attempted to trick Heroku into thinking that our front end files are PHP. Since, these files are not completely static, this trick was not working. |
postgres update the value of hstore with old partial value, in rails Posted: 01 Sep 2016 06:53 AM PDT I've been trying to update the wrong migrated values of the hash store, "area_unit"=>NULL, "building_type"=>"{:building_type=>\"apartment\"}", to "area_unit"=>NULL, "building_type"=>"apartment"}", the value should stay the same, I don't want to use regular expression. is there an easy way for doing that ? I'm working with ruby. |
Run code if x times if item present Posted: 01 Sep 2016 06:58 AM PDT From my last question, I cant seem to get what I want. Below explains a lot better: external = ["apple"] internal = ["grapes", "pear", "mangoes", "apple"] external.each do |fruit| if not internal.include?("apple") # fruit will be in place of apple. puts "yes" # run code end end So far this is printing once. How to get it print three times? In English I'm saying if apple is present, leave apple alone, give me the others, and run the code below. If 4 items are there and one is apple , run code three times. If apple not present, run code 4 times. I hope this is very clear. Thanks I need to be 100% precise: Internal is a Model (postgres) External is shopify api (array) I have saved shopify's product id in my database, Bar , on a column called foo . Bar.first.foo gives me the shopify's id. Bar will have other object with/without the shopify id. So If shopify is there, give me the rest. This is why I came up with: external.each do |fruit| if not internal.include?("apple") # fruit will be in place of apple. puts "yes" # run code end end |
Ruby on rails not loading layout responsive for mobile devices Posted: 01 Sep 2016 06:17 AM PDT Its been a Day since i am facing this issue . and i have no clue why this happening. i am trying to import a layout in the rails 4 application. I am using bootstrap.css and responsive.css i guess my responsive.css file is not working in my rails app i can explain clearly by these images when i load the layout by just clicking on the html file without the rails app this is the layout i am getting on mobile devices and by importing the layout in the rails this is what i am getting as by the rails app when it will run on mobile devices everything will look small i am seeing no error in the browser console all my assets are loading correctly . but what i think this may be the error of @media (max-width: px) { } but i am not sure . and i have already included <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> in the head tag. can someone please help me with this so my app can be perfectly responsive |
devise_token_auth email sending issue Posted: 01 Sep 2016 05:50 AM PDT I'm using devise_token_auth in my app. When user registers, it automatically sends confirmation email. from https://github.com/lynndylanhurley/devise_token_auth/blob/master/app/controllers/devise_token_auth/registrations_controller.rb # ..code unless @resource.confirmed? # user will require email authentication @resource.send_confirmation_instructions({ client_config: params[:config_name], redirect_url: @redirect_url }) # ..code And I get 500 error. I, [2016-09-01T12:32:06.142856 #15153] INFO -- : [07ca58ab-1797-4edb-99bb-c7d408bfd2c9] Completed 500 Internal Server Error in 31331ms (ActiveRecord: 8.4ms) F, [2016-09-01T12:32:06.145874 #15153] FATAL -- : [07ca58ab-1797-4edb-99bb-c7d408bfd2c9] F, [2016-09-01T12:32:06.146192 #15153] FATAL -- : [07ca58ab-1797-4edb-99bb-c7d408bfd2c9] Net::OpenTimeout (execution expired): F, [2016-09-01T12:32:06.146249 #15153] FATAL -- : [07ca58ab-1797-4edb-99bb-c7d408bfd2c9] F, [2016-09-01T12:32:06.146292 #15153] FATAL -- : [07ca58ab-1797-4edb-99bb-c7d408bfd2c9] /home/deploy/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/smtp.rb:542:in `initialize' ... As you can see from the log it times out Net::OpenTimeout (execution expired): But when I run User.last.send_confirmation_instructions from console it sends the email how it is suppose to be. What am I suppose to do? Thanks! |
Ruby on Rails: Why doesn't my image appear inline in the email? Posted: 01 Sep 2016 05:48 AM PDT Within my Ruby on Rails application I am trying to embed a logo in an email to be displayed inline, but for some reason it does not appear (please see the below image). I have tried to follow the answers on this Stack Overflow question What is the right way to embed image into email using Rails? but cannot get it to work. My mailer is as follows: class UserEmails < ApplicationMailer def send_email(email, unsubscribe) @url = 'http://localhost:3000/users/login' @email = email @unsubscribe = unsubscribe attachments.inline['logo.jpg'] = File.read('app/assets/images/logo.jpg') mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject) end end And my email view: <!DOCTYPE html> <html> <head> <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' /> </head> <body> <h1><%= @email.subject %></h1> <p> <p> To <%= image_tag attachments['logo.jpg'].url %> <%= link_to "Unsubscribe", settings_unsubscribe_url(id: @unsubscribe) %> </body> </html> Is anyone able to tell me why this isn't working? |
How to upload files to the server in rails? Posted: 01 Sep 2016 05:46 AM PDT i am willing to upload the file to the server without using any gem. Following is what i have tried: the following is the function that i have created in modal: def self.file_upload(uploaded_file) puts uploaded_file file = Tempfile.new(uploaded_file, 'http://52.41.99.60/GEMWebservices/Image') returning File.open(file.path, 'w') do |f| f.write file.read f.close end end I have used the above function in create acrion as follows: @file_upload = User.file_upload(params[:uploaded_file]) But i get the following error: unexpected prefix: #<ActionDispatch::Http::UploadedFile:0x007fa0909fbe00 @tempfile=#<Tempfile:/var/folders/tt/d903z3v94sbgr8yymqxn_m0m0000gn/T/RackMultipart20160829-27648-gzgzt8.jpeg>, @original_filename="kaka.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"kaka.jpeg\"\r\nContent-Type: image/jpeg\r\n"> Can any one help me out? Thank you in advance. |
RAILS Save csv file on server Posted: 01 Sep 2016 05:54 AM PDT In my rails app, I can download data as csv file. This is my current code response_to do |format| format.csv {send_data #MY_DATA#} end Instead of this code, I want to save the csv file on server. How can I generate csv file and save the file on the server Thanks |
Rails and Heroku - Rake db:seed only populates some databases and not others? Posted: 01 Sep 2016 05:51 AM PDT I have a rails app that I've been working on locally and have deployed to heroku. I have a lot of data that needs to be seeded that has worked well locally, with a small issue that I didn't pay much mind to. Basically I have a number of tables covering: - Feature,
- Addon,
- Budget,
- ProjectType
- Industry
etc. When I create/reset the local database and run the rake db:seed it seeds perfectly to each database. However, as its a WIP I keep adding new tables and running the seed rake db:seed, and noticed that where it should have been doubling up all of the seeded data (because I never cleared the data), it actually only duplicated this info on the Addon, and Feature tables. The other tables were unchanged. I thought nothing of it, until I started trying to run heroku run rake db:seed to populate my production database and noticed that in the logs it was also only populating the Addon and Feature tables, and skipping over the rest. An extract from some of my seed file (I've shortened with ... as they are very repetitive but all the same): #Populate the features table Feature.destroy_all Feature.create(id: 1, name: 'Contact form') Feature.create(id: 2, name: 'Blog') Feature.create(id: 3, name: 'Mailing list signup') ... ... #Populate the addons table Addon.destroy_all Addon.create(id: 1, name: 'Domain registration') Addon.create(id: 2, name: 'Hosting') Addon.create(id: 3, name: 'Create content') ... ... #Populating the industries table Industry.destroy_all Industry.create(id: 1, name: 'Accounting') Industry.create(id: 2, name: 'Airlines') Industry.create(id: 3, name: 'Alternative Medicine') ... ... # Populating the budgets table Budget.destroy_all Budget.create(id: 1, name: 'Micro', minimum: 250, maximum: 1000) Budget.create(id: 2, name: 'Simple', minimum: 1000, maximum: 2500) ... ... I noticed that when I try populate the heroku database with heroku run rake db:seed the data all seems to "rollback". Here is an extract from the console: First I run heroku run rake db:migrate D, [2016-09-01T12:24:31.463009 #3] DEBUG -- : (1.8ms) SELECT pg_try_advisory_lock(4467995963834188590); D, [2016-09-01T12:24:31.476939 #3] DEBUG -- : ActiveRecord::SchemaMigration Load (1.9ms) SELECT "schema_migrations".* FROM "schema_migrations" D, [2016-09-01T12:24:31.507280 #3] DEBUG -- : ActiveRecord::InternalMetadata Load (1.8ms) SELECT "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2 [["key", :environment], ["LIMIT", 1]] D, [2016-09-01T12:24:31.518500 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:24:31.522494 #3] DEBUG -- : (1.7ms) COMMIT D, [2016-09-01T12:24:31.524504 #3] DEBUG -- : (1.8ms) SELECT pg_advisory_unlock(4467995963834188590) Then I run rake heroku run rake db:seed For the tables where it doesn't work it seems to do this: D, [2016-09-01T12:27:28.229540 #3] DEBUG -- : ActiveRecord::SchemaMigration Load (2.2ms) SELECT "schema_migrations".* FROM "schema_migrations" D, [2016-09-01T12:27:28.261528 #3] DEBUG -- : Budget Load (2.3ms) SELECT "budgets".* FROM "budgets" D, [2016-09-01T12:27:28.293954 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.320090 #3] DEBUG -- : (1.9ms) ROLLBACK D, [2016-09-01T12:27:28.322421 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.325418 #3] DEBUG -- : (1.8ms) ROLLBACK D, [2016-09-01T12:27:28.327617 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.331031 #3] DEBUG -- : (1.8ms) ROLLBACK D, [2016-09-01T12:27:28.333423 #3] DEBUG -- : (1.8ms) BEGIN D, [2016-09-01T12:27:28.338379 #3] DEBUG -- : (2.5ms) ROLLBACK D, [2016-09-01T12:27:28.340601 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.344061 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.346208 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.349342 #3] DEBUG -- : (1.8ms) ROLLBACK D, [2016-09-01T12:27:28.353205 #3] DEBUG -- : (3.4ms) BEGIN D, [2016-09-01T12:27:28.358254 #3] DEBUG -- : (2.5ms) ROLLBACK D, [2016-09-01T12:27:28.360392 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.363406 #3] DEBUG -- : (1.8ms) ROLLBACK D, [2016-09-01T12:27:28.365488 #3] DEBUG -- : (1.6ms) BEGIN D, [2016-09-01T12:27:28.367862 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.369869 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.372657 #3] DEBUG -- : (1.8ms) ROLLBACK D, [2016-09-01T12:27:28.378093 #3] DEBUG -- : Industry Load (2.1ms) SELECT "industries".* FROM "industries" D, [2016-09-01T12:27:28.393455 #3] DEBUG -- : (1.8ms) BEGIN D, [2016-09-01T12:27:28.409125 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.411280 #3] DEBUG -- : (1.6ms) BEGIN D, [2016-09-01T12:27:28.414223 #3] DEBUG -- : (1.6ms) ROLLBACK D, [2016-09-01T12:27:28.416244 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.419335 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.421511 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.425412 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.427570 #3] DEBUG -- : (1.7ms) BEGIN D, [2016-09-01T12:27:28.431136 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.433536 #3] DEBUG -- : (2.0ms) BEGIN D, [2016-09-01T12:27:28.438208 #3] DEBUG -- : (1.7ms) ROLLBACK D, [2016-09-01T12:27:28.440437 #3] DEBUG -- : (1.7ms) BEGIN And then when it passes over the features and addons, it seems to work fine: D, [2016-09-01T12:27:29.506570 #3] DEBUG -- : SQL (1.9ms) INSERT INTO "features" ("id", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["id", 1], ["name", "Contact form"], ["created_at", 2016-09-01 12:27:29 UTC], ["updated_at", 2016-09-01 12:27:29 UTC]] D, [2016-09-01T12:27:29.509515 #3] DEBUG -- : (2.5ms) COMMIT D, [2016-09-01T12:27:29.512944 #3] DEBUG -- : (2.2ms) BEGIN D, [2016-09-01T12:27:29.516551 #3] DEBUG -- : SQL (1.9ms) INSERT INTO "features" ("id", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["id", 2], ["name", "Blog"], ["created_at", 2016-09-01 12:27:29 UTC], ["updated_at", 2016-09-01 12:27:29 UTC]] D, [2016-09-01T12:27:29.519489 #3] DEBUG -- : (2.5ms) COMMIT D, [2016-09-01T12:27:29.522216 #3] DEBUG -- : (2.5ms) BEGIN D, [2016-09-01T12:27:29.526125 #3] DEBUG -- : SQL (1.9ms) INSERT INTO "features" ("id", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["id", 3], ["name", "Mailing list signup"], ["created_at", 2016-09-01 12:27:29 UTC], ["updated_at", 2016-09-01 12:27:29 UTC]] I did notice that of the tables, Addons and Features both have a has_and_belongs_to_many association with other tables while the rest of the tables that aren't working have a belongs_to association with some other tables. Not sure if that is just a coincidence? Thanks for any help! |
Optimize long chain of associations Posted: 01 Sep 2016 05:51 AM PDT I have a Customer that goes to the Shop which has a Manager. Both Customer and Manager are from People model, different roles only. What is the best way to get a Manager from Customer? Right now I have this solution which is very slow: shop_manager = customer.shop.people.select{|p| p.has_role?(:manager)}.first person.rb: belongs_to :shop shop.rb: has_many :people Roles are assigned using rolify gem. |
Rails button to approve gamer status Posted: 01 Sep 2016 05:45 AM PDT I have a method like this: gamer.rb def approve_gamer(type) where(type: type).last.update(status: 'approved') end and I want to make a button for each type to call approve_gamer('type') . Should it be button_to [:approve_gamer, gamer] or link_to ... class: "btn btn-default" ? How do I pass the type parameter there? |
I have two separate git repos, one for an Angular front end and another for a Rails 5 API. How should I structure the deploy process? Posted: 01 Sep 2016 04:29 AM PDT I have an Angular 1.4.7 app in one git repo and a Rails 5 API in another repo. The Angular app talks to the API and my team makes regular changes to both sides of the app. What would be a clean way to structure the deploy process on Heroku? |
Rails - Table listing - value as checkbox Posted: 01 Sep 2016 04:48 AM PDT In a listing (index.html.erb), how can I display the value of a boolean field as a check_box? <td><%= annotation.active %></td> currently it lists as "true" / "false". |
Bank payment transfer via stripe in rails Posted: 01 Sep 2016 06:13 AM PDT Hello there i want to transfer money from stripe account to customer account. Currently i am using this tecnique to transfer money to customer account. But i want to use the ach method for tranfer the money from stripe account to customer account so what should i do for that. Currently i am using this method: transection_controller.rb: @pay = Stripe::Transfer.create(amount: @offer_transaction.amount.to_i, currency: 'usd', destination: @user.stripe_connect_account_id, description: 'Transfer for test@example.com') I am new to rails and don't have that much idea. Any help should be thankful. |
Saving record to rails database from python script Posted: 01 Sep 2016 04:15 AM PDT I have Rails application with classic forum models like Post , Topic . Then I have python script using praw to download certain posts and topics from Reddit. (I know that I can use ruby version, but lets say we have to use this python script) I'd like to put them directly into my rails database. I can save them in json format and create rake task to upload them into my database, but I think I don't need to add this complexity and should somehowe save them directly to my rails db from this python script. How can I do this? |
How to put filename in cron job (rails)? Posted: 01 Sep 2016 04:17 AM PDT I am using whenever gem. I am calling runner to run job. I called runner for the same job by 3 type. I am not sure which one working here. I used command whenever --update-crontab project_name then crontab -l Schedule.rb set :output, 'log/whenever.log' every 1.days , :at => '03:51 pm' do runner "SomeJob.perform_later", filename: '/app/jobs/some_job.rb' end every 1.days , :at => '03:51 pm' do runner "SomeJob.perform_later", filename: './app/jobs/some_job.rb' end every 1.days , :at => '03:51 pm' do runner "SomeJob.perform_later" end Also these ran only once. I am having difficult time to debug here. Can anyone tell which one is correct? Also what is the correct way to debug in this scenario? Running crontab -l gives me this - 51,51,51 16 * * * /bin/bash -l -c 'cd /home/rahul/orthoweb && bin/rails runner -e production '\''InvestigationStopJob.perform_later'\'' >> log/whenever.log 2>&1 To run in development environment I ran this command - whenever --update-crontab --set environment='development' But this gives me this message - ## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated. |
Why Rails can use `if` as hash key but not in Ruby Posted: 01 Sep 2016 05:37 AM PDT In pure Ruby irb, one cannot type {if: 1} . The statement will not terminate, because irb thinks if is not a symbol but instead the beginning of an if statement. So why can Rails have before_filter which accept if as parameters? The guide have codes like: class Order < ApplicationRecord before_save :normalize_card_number, if: :paid_with_card? end Same thing happens to unless as well. |
Is it safe to use find params[:id] in Rails? Posted: 01 Sep 2016 05:34 AM PDT Expressions like the following are common in Rails: @project = Project.find params[:id] # example 1 @project = current_user.projects.find params[:project_id] # example 2 However I realize that find also accepts arrays! That would mean unexpected and potentially dangerous behavior of code, which is written with the assumption that @project is a single project, not an array. Now the question is: - should I typecast
params[:id].to_s every time I use it in find ? - should I use strong parameters with
find in order to avoid arrays? find params.permit(:id)[:id] )? (better than to_s if you don't want to convert nil to "" ) - are there any other alternatives or common practices?
The above vulnerability seems to be present only if the routes doesn't define a param with that name. For example: # SAFE routes.rb resources :projects # projects_controller.rb Project.find params[:id] The query /projects/3?id[]=4&id[]=5 produces only {id: 3} as a param. This would make using Project.find params[:id] safe: however I cannot find any documentation for this behavior and I don't know if it's safe to rely on it: maybe it's just by chance. Furthermore the following is not equivalent at all and would create a vulnerability in the controllers: # Likely UNSAFE routes.rb # E.g.: # /projects?id=3 => params = {id: 3} # /projects?id[]=3&id[]=4 => params = {id: [3, 4]} put '/projects' => 'projects#update' |
Rails WHERE query on has_many relation works incorrect? Posted: 01 Sep 2016 03:43 AM PDT Cheers! Let's say I have User that has_many Accounts , Account model has logged_in (boolean) field. I wrote a AR query: User.joins(:accounts).where(accounts: { logged_in: false }) , right? But then I check it User.joins(:accounts).where(accounts: { logged_in: false }).first.accounts.pluck(:logged_in) And could see that there are some accounts with mobiles.logged_in = true values. (0.1ms) SELECT "accounts"."logged_in" FROM "accounts" WHERE "accounts"."user_id" = $1 [["user_id", 373]] false false true Why? |
How to load module ApplicationHelper into config/environments/development.rb? Posted: 01 Sep 2016 03:03 AM PDT I'm trying to load the ApplicationHelper module inside config/environments/development.rb : Rails.application.configure do ... include ApplicationHelper ...(here I want to call my functions from ApplicationHelper) end I need to call there my functions defined in ApplicationHelper. But when I start the rails server, I get the error: undefined method `include' for # (NoMethodError) How to include the ApplicationHelper module the correct way? |
PG::UndefinedColumn: ERROR: column users.contact_id does not exist on ActiveAdmin Posted: 01 Sep 2016 06:27 AM PDT I got this error when going to one my ressources called "Fils": PG::UndefinedColumn: ERROR: column users.contact_id does not exist LINE 1: SELECT "users".* FROM "users" WHERE "users"."contact_id" = ... ^ : SELECT "users".* FROM "users" WHERE "users"."contact_id" = $1 LIMIT 1 I don't understand why the query looks on user.contact_id instead of fil.contact_id (I'm beginning in rails but i don't think it's the good behavior) Fil table on schema.rb : create_table "fils", force: :cascade do |t| t.integer "contact_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" t.string "channel" end Fil model : class Fil < ActiveRecord::Base before_validation :check_or_connect_messageries, :if =>:new_record? has_one :contact, class_name: "User", :foreign_key => "contact_id" has_one :user, class_name: "User", :foreign_key => "user_id" validates :contact_id, presence: true validates :user_id, presence: true before_create :set_channel after_find :set_channel # des fois que User model : class User < ActiveRecord::Base before_validation :check_genres before_validation :set_image before_validation :init_attrs before_save :create_mangopay_bank_account before_create :set_name before_create :create_mangopay after_create :set_centres_interets after_create :set_preferences_musicales after_create :check_on_create after_update :check_on_update devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable has_one :preferences_voyage, dependent: :destroy has_one :verification, dependent: :destroy has_many :badges, dependent: :destroy has_many :favoris , dependent: :destroy has_many :centres_interets, dependent: :destroy has_many :preferences_musicales, dependent: :destroy has_many :recommandations, dependent: :destroy has_many :reputations, dependent: :destroy has_many :reservations, dependent: :destroy has_many :routes, dependent: :destroy has_many :trajets_reguliers, dependent: :destroy has_many :vehicules, dependent: :destroy has_many :notifications, dependent: :destroy validates :date_naissance, presence: true validates :first_name, presence: true validates :last_name, presence: true attr_accessor :points_communs attr_accessor :modele # created/booked/archived attr_accessor :peut_laisser_commentaire attr_accessor :est_abonne attr_accessor :est_bloque attr_accessor :a_vehicule admin/user.rb : ActiveAdmin.register User do menu parent: "Utilisateurs" permit_params :name, :nickname, :email , :image, :genre,:statut, :fume, :etudes index do selectable_column id_column column :name column :nickname column :email column "Image" do |user| image_tag user.image, size: "50" end column :genre column :statut column :fume column :etudes column :profession actions end end |
Delayed::Worker.new(queues: 'bulk_email_dj').work_off Posted: 01 Sep 2016 03:02 AM PDT I am writing test cases to verify email sent successfully or not? i am using delayed_job gem, but i have no idea how delayed job process queues. When i try to run delayed_jobs in my test cases with following Delayed::Worker.new(queues: 'bulk_email_dj').work_off Then it returns [0,0], no success and no failure. But when i try Delayed::Worker.new.run(Delayed::Job.last) Then it runs last delayed job. But i want multiple delayed jobs to be run, i-e all bulk_email_dj jobs Any help would be highly appriciated. |
No comments:
Post a Comment