Michael Hartls RoR tutorial: scss is not targeting input Posted: 12 Jul 2016 08:05 AM PDT I am writing with regards to a problem I am facing while working through Michael Hartl's tutorial for Ruby on Rails. The problem is that css does not change appearance of input field for password confirmation. All other input fields appearances are affected by the css rules. Please find pictures and files below: What I get: // app/assest/stylesheets/custom.scss @mixin box_sizing { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* forms */ input, textarea, select, .uneditable-input { border: 1px solid #bbb; width: 100%; height: auto; margin-bottom: 15px; @include box_sizing; } # app/views/users/new.html.erb <% provide(:title, 'Sign up') %> <h1>Sign up</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_for(@user, url: signup_path) do |f| %> <%= render 'shared/error_messages' %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> <%= f.label :password %> <%= f.password_field :password, class: 'form-control' %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation, class: 'form_control' %> <%= f.submit "Create my account", class: "btn btn-primary" %> <% end %> </div> </div> I've attempted to comment out line @include box_sizing; or give fixed height like height: 25px; , but it didn't help. Any help would be appreciated! |
Capybara not waiting on expect Posted: 12 Jul 2016 08:04 AM PDT I have a page with a link that opens a bootstrap modal with a simple input field. I'm having a hard time understanding why Capybara doesn't wait for the modal to open, and fails immediately. I added expect(page).to have_content('Did you') so capybara will wait a few seconds until the modal is shown. But for some reason it's not waiting and raises Capybara::ExpectationNotMet: expected to find text "Did you" in ...." If I put a sleep of 1 second it will then find the modal, but it's not good enough because then a DB clean callback found in my spec_helper.rb is called: config.after(:each) do DatabaseCleaner.clean end This is the spec: RSpec.describe "follower button", type: :request do it "sends email #15B to owner", :js do using_wait_time 20 do FactoryGirl.create(:apartment_with_event) visit apartment_path(Apartment.last) click_on 'follow-events' expect(page).to have_content('Did you') within('#follow-events-modal') do fill_in 'follower-email-signup-mail', with: 'follower@example.com' click_button 'follower-signup-submit' end expect(page).to have_content(I18n.t("followers.create.title_success")) expect(Follower.all.count).to eq(1) end end end I also set Capybara.default_max_wait_time = 10 in spec_helper.rb, even though it should wait for 20 seconds for this example. I really spent hours trying to discover why it's happening, while other examples run just fine. |
delete has_many through relationship Ruby on Rails Posted: 12 Jul 2016 08:03 AM PDT I'ved got a Ruby on Rails app I have Block that has_many Unit that has_many User through user_unit_assocs. The model is define as such. class Block < ActiveRecord::Base has_many :units, dependent: :destroy class Unit < ActiveRecord::Base belongs_to :block has_many :users, :through => :user_unit_assocs, dependent: :destroy has_many :user_unit_assocs, dependent: :destroy class User < ActiveRecord::Base has_many :units, :through => :user_unit_assocs has_many :user_unit_assocs, dependent: :destroy The problem is when I delete Block - unit gets deleted - user_unit_assoc gets deleted - BUT the user of the unit DOES NOT GET DELETED How do I solve this problem to make sure it cascade block to user as well. Problem is the through but I cant change now the table structure, how can I solve these dependent records deletion properly. Thanks. |
How to associate between 2 models which are not directly related in rails? Posted: 12 Jul 2016 08:01 AM PDT I have 5 tables/models. Here are the structures. 1. application id name 2. profiles id name app_id (Foreign key application table: id) 3. app_profiles id profile_id (Foreign key profile table: id) app_id (Foreign key application table: id) 4. segments id app_id (Foreign key application table: id) 5. profile_segments id app_profile_id (Foreign key app_profile table: id) segment_id (Foreign key segment table: id) Here are my associations: application.rb has_many :profiles, through: :app_profiles has_many :segments has_many :app_profiles profile.rb has_many :applications, through: :app_profiles has_many :app_profiles app_profile.rb belongs_to :profile belongs_to :application has_many :segments, through: :profile_segments has_many :profile_segments segment.rb has_many :profiles, through: :app_profiles has_many :app_profiles, through: :profile_segments has_many :profile_segments belongs_to :application profile_segment.rb belongs_to :app_profile belongs_to :segment Now the problem is I need to make an association between profile and profile_segment. Can this be done? If so how? Thanks in advance for helping me out! |
How to create and where to run a daily job to copy production database from Linode to Heroku? Posted: 12 Jul 2016 07:59 AM PDT For historical reasons Heroku is where are reporting database is located, which is a direct copy of production from Linode. I currently run commands locally every day to copy the Linode database from Linode server to local drive and then push it to Heroku. I need to automate this somehow so it runs 'somewhere' every day - but where? I know about cron jobs etc and also that you can run workers on Heroku, but I really don't know what is the best/recommended way to go about this and would like to see what others recommend. I tried googling but cannot seem to find anything that points me in the right direction - the results are always heroku to heroku copying! Perhaps someone on here knows of some tools/services that might help automate this task? |
How to alias joins in rails 2.3 Posted: 12 Jul 2016 07:58 AM PDT In my app I want to create a named scope to use in queries across the app that gets data from a has_many association. I run into issues when elsewhere I :include that same association, leading to mysql errors Mysql::Error: Not unique table/alias: 'foo' Here is what my named scope looks like: named_scope :single_foo, :joins => :foo, :group => "foo.blip_id", :having => "count(foo.blip_id) = 1" How can I update my :joins statement to make an alias for foo so that in queries as below I don't have unique table errors? Blip.single_foo.find(:all, :include => [ :foo ], :conditions => (......)) Also, bonus points if somebody can guide me to a simpler named scope, I want to only select Blips that have a single Foo. |
Trying to dry up code - Variable is not passing to a partial. Posted: 12 Jul 2016 08:00 AM PDT I am trying to dry up code for a couple of reports. I took the table header code and put that in a partial. That works fine when I call that with a render partial. However, when I try to move the code for the body of the table, I am getting a 'something went wrong' error. My original code that works is <% @complaints.each do |complaint| %> <% if complaint.product_name == $complaint_group_name then %> <tr> <td><%= link_to complaint.id, complaint %></td> <td style="text-align: right;"><%= complaint.length %></td> <td style="text-align: center;"><%= complaint.disposition %></td> <td width="20%"><%= complaint.sales_order %></td> . . . <% end %> <% end %> The code that is not working is when I've moved that to a partial and try to render a partial <% @complaints.each do |complaint| %> <% if complaint.product_name == $complaint_group_name then %> <%= render :partial => 'report_body' %> <% end %> <% end %> I see an error of I, [2016-07-12T10:25:09.046754 #95324] INFO -- : Rendered complaints/report_by_product.html.erb within layouts/application (359.4ms) I, [2016-07-12T10:25:09.046754 #95324] INFO -- : Completed 500 Internal Server Error in 375ms (ActiveRecord: 140.6ms) F, [2016-07-12T10:25:09.046754 #95324] FATAL -- : ActionView::Template::Error (undefined local variable or method `complaint' for #<#<Class:0x51caab8>:0x95242f8>): 1: 2: 3: <tr> 4: <td><%= link_to complaint.id, complaint %></td> 5: <td style="text-align: right;"><%= complaint.length %></td> 6: <td style="text-align: center;"><%= complaint.disposition %></td> 7: <td width="20%"><%= complaint.sales_order %></td> app/views/complaints/_report_body.html.erb:4:in `_app_views_complaints__report_body_html_erb__209592603_78833796' Apparently the |complaint| part of the block does not get recognized by the partial. I either need to be able to pass this or include it in the partial - but then it gets messy because the grouping for each report would need to be handled in the partial. The short question is can I pass |complaint| to the partial? |
syntax error near unexpected token `newline' (when install XAlign) Posted: 12 Jul 2016 07:44 AM PDT I want to install XAlign,there are some error. qzslz-2:~ qzslz$ curl github.so/XAlign/build/install.sh | sh error : sh: line 1: syntax error near unexpected token newline' sh: line 1: ' I don't know how to solve the problem,please help me!thanks! |
Using axlsx partials Posted: 12 Jul 2016 07:43 AM PDT I am using axlxs and axlsx_rails . I can create inline spreadsheets no problem - for example I have an index.xlsx.axlsx file etc. The problem is I have another action the uses the exact same code so I tried creating a partial _export.xlsx.axlsx and moving my code in there. I then replaced index.xlsx.axlsx with render 'export' . I get an excel spreadsheet generated by Excel says it's corrupted. I can just duplicate my code in another file but there must be an easier way to do this. |
Routing error updating/creating record Posted: 12 Jul 2016 07:40 AM PDT I have what seems to me as a weird routing error that I can't seem to resolve. I'm using Rails 4.2.6 and generating a scaffold for customers. I'm able to view a listing of customers but when I edit a customer I get an error No route matches [POST] "/customers/49" Everything is pretty much what the scaffolding created though I did change my routes to this: resources :customers do resources :comments, only: [:new, :create, :edit, :update] end but I tried it with the scaffolding default as well and receive the same error. These are the routes for customers: customers GET /customers(.:format) customers#index POST /customers(.:format) customers#create new_customer GET /customers/new(.:format) customers#new edit_customer GET /customers/:id/edit(.:format) customers#edit customer GET /customers/:id(.:format) customers#show PATCH /customers/:id(.:format) customers#update PUT /customers/:id(.:format) customers#update DELETE /customers/:id(.:format) customers#destroy The generated HTML for the "edit" page shows it is a post request <form class="edit_customer" id="edit_customer_49" action="/customers/49" accept-charset="UTF-8" method="post"> and the same for the "new" page <form class="new_customer" id="new_customer" action="/customers" accept-charset="UTF-8" method="post"> For the most part everything is what the scaffolding produced so I'm not sure why I'm getting the error. Why is the generated HTML using a POST and how can I get this working? Thanks for helping a Rails newbie. |
Having a hash, set object properties in Ruby Posted: 12 Jul 2016 07:58 AM PDT Having a hashmap, such as: {:foo => 1, :bar => 2} in Ruby, is there an easy way to assign those values as properties of the object, to automatically cause this to happen: obj.foo = 1 obj.bar = 2 To be precise, some Ruby-idiomatic way of doing: hashmap.each { |k,v| obj.send("#{k}=", v) } obj is an object that doesn't inherit ActiveModel and it's not a Struct and I can't control it's type as it's coming from a third party library. I'm using Rails, so if the answer comes from Rails, that's accetable. |
base 64 photo to paperclip rails image Posted: 12 Jul 2016 07:53 AM PDT I have a rails app and I am receiving a base64 encoded string that is an image from an ios app. I am trying to convert it to a paperclip image. So far I have: module Api module V1 class MyController < BaseController def image_build begin token = request.headers["HTTP_TOKEN"] @user = User.find_by(user_token: token) @decoded_image = Base64.decode64(params[:image_data]) puts @decoded_image[0, 50] @new_stand = Stand.create(:user_id => @user.id, :avatar => @decoded_image) ... which outputs: iVBORw0KGgoAAAANSUhEUgAAAPsAAACxCAYAAAACscusAAAAAX �PNG IHDR��ˬsRGB��� Completed 500 Internal Server Error in 90ms (Views: 3.1ms | ActiveRecord: 1.1ms) How do I convert the base64 string to a proper image file in rails? I have paperclip running from this gem: gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" Notes The images sent over can be any image from an ios phone so the type can change. I would like to support .gif, .png, .jpg, and jpeg. In IOS I send over the information like this: @IBOutlet var image: UIImage @IBAction func Build(sender: AnyObject) { let image_data = UIImagePNGRepresentation(image.image!) self.service.createNewImage(notifier: notifier, image: image_data!) } then let strBase64:String = image.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) let dataDictionary = ["image_data": strBase64] self.post("image/build", data: dataDictionary).responseJSON |
Rails 5 ActionController::InvalidAuthenticityToken error Posted: 12 Jul 2016 07:53 AM PDT I have a rails application which I am planning to upgrade to rails 5. I am using devise(v4.2.0) along with rails(v5.0.0). As suggested in devise README.md file, I tried moving the protect_from_forgery above the before_filter but still when I am trying to login or update my bug I get an error ActionController::InvalidAuthenticityToken My Application Controller is class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) devise_parameter_sanitizer.permit(:account_update, keys: [:name]) end end And my other BugController is class BugsController < ApplicationController protect_from_forgery prepend: true, with: :exception before_action :authenticate_user! before_action :set_bug, only: [:show, :edit, :update] def update respond_to do |format| if @bug.update(bug_params) format.html { redirect_to @bug, notice: 'Bug was successfully updated.' } format.json { render :show, status: :ok, location: @bug } else format.html { render :edit } format.json { render json: @bug.errors, status: :unprocessable_entity } end end end private def bug_params params.require(:bug).permit(:product, :component, :title, :description, :status_id, :created_by_id, :assigned_to_id) end end |
Check if a table value in one model matches a table value in a different model Posted: 12 Jul 2016 07:34 AM PDT This question is kind of hard to ask, but basically, I have a Class model and a User model, each Class table has a token, and so does each User one. After the user submits a sign up form, how would I set the value of the users class_id in the create action? I've tried <%= f.hidden_field :app_id, :value => App.find_by_token(params[:key]) %> , but this doesn't work. Sorry for the long and confusing question, will be glad to answer more. Thanks in advance for any answers |
What is the best way to precompile assets only once in multi-machine environment? Posted: 12 Jul 2016 07:09 AM PDT I've 3 EC2 machines (the number can vary in future) in my production environment. Following are my configurations, rails version = 3.1.4 ruby version = 1.9.3 capistrano version = 2.15.9 Currently, I'm using set :deploy_via, :remote_cache , as one of the settings & one of the capistrano task is as follows, desc "Precompile assets after deploy" task :precompile_assets do run <<-CMD cd #{ current_path } && bundle exec rake assets:precompile:primary RAILS_ENV=#{ rails_env } CMD end The problem I'm facing is when I deploy my application using cap deploy with this in deploy.rb file, precompile is running 3 times! It is logical. Can I optimize it somehow? Ideally, I want to do pre-compile it on my local/build machine and then scp the precompiled assets to all my production machines. Can this be achieved using capistrano? If yes, how? |
Cached fragment never expires Posted: 12 Jul 2016 06:44 AM PDT I have a rails application for managing public events. Within the a view I am trying to cache a fragment which expires every 8 hours. The fragment caches successfully but never expires. Looking at the site today the fragment is showing events from the 23rd June, which is the last time I manually flushed the fragment cache. I'm currently using the following snippet which renders a list of event titles and dates: - cache('sidebar-cache', :expires_in => 8.hour) do = render "shared/sidebar_festivals" I have also tried the following (24 hours instead of 8) with the same issue: - cache "sidebar_cache", expires: 1.day.from_now(Time.now.beginning_of_day) = render "shared/sidebar_festivals" I have caching enabled in the production.rb config file: config.action_controller.perform_caching = true Is there something else I need to enable or do for fragment caching to expire? I'm using Rails 4.2.1 Any help is much appreciated. |
How to handle validations between associated objects? Posted: 12 Jul 2016 06:47 AM PDT I am having difficulty in validating two objects across some complex associations. Here's an example of what I have: car.rb class Car has_many :passengers end passenger.rb class Passenger belongs_to :car belongs_to :info end Validations I need to do: - The number of passengers is limited
- Passengers have an association to an object called
Info that has "Employer" as a string. All passengers must have the same employer. The interface has a multiselect box to choose passengers. Once you're done selecting the passengers, you click "Create" (or "Update", which has it's own set of problems). When the controller tries to create the Car , it needs to run the car validations, then the passenger validations need to pass (employer check), and then the car needs to also ensure it's not exceeding the passenger count. If one of these fails, I need to reset and take them back to the new page. During update, if it fails, I need to restore the original passengers to the car. I'm not sure how to perform the validations without actually saving the objects to the database though. In addition, once the objects are saved to the database, if the validations fail, then I don't know how to restore the previous passengers. How can I validate associated objects before saving them to the database? |
Display Decimals & Currency Ruby on Rails Posted: 12 Jul 2016 06:58 AM PDT I have a local environmental variable in my show.html.erb @experiment.baseline_conversion_60 The baseline_conversion_60 is stored as a decimal in my database. When I display this variable in my show it always displays as a whole number. How can I show it as a decimal? I also have another variable that is stored as a decimal, but I would like to display as currency. Any suggestions would be greatly appreciated! |
Devise_Invitable Custom Parameters leading to with_indifferent_access Posted: 12 Jul 2016 06:33 AM PDT Working with Devise_invitable to send invitations to users however I would like the inviting to be done by Admins only (have this implemented already) and I would like to assign attributes to my invitees. My InvitationsController looks as follows: class InvitationsController < Devise::InvitationsController def after_invite_path_for(resource) edit_user_url(@user) end private def invite_params devise_parameter_sanitizer.for(:invite) do |u| u.permit(:name, :email, :invitation_token) end end def update_sanitized_params devise_parameter_sanitizer.for(:accept_invitation) do |u| u.permit(:name, :email, :password, :password_confirmation, :invitation_token) end end end This controller links into the default devise_invitable on #Create and passes an error of "Undefined Method `with_indifferent_access' My View looks like so: <h2><%= t "devise.invitations.new.header" %></h2> <%= form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %> <%= devise_error_messages! %> <% resource.class.invite_key_fields.each do |field| -%> <div class = "field"> <span class = "glyphicon glyphicon-user"></span> <%= f.text_field :name, class: "login", placeholder: "Name"%> </div> <div class = "field"> <span class = "glyphicon glyphicon-envelope" aria-hidden="true"></span> <%= f.email_field :email, class: "login", placeholder: "Email"%> </div> <div class = "field"> <h3>what locations does the user need access to?</h3> <%= f.fields_for :location do |h| %> <% Location.all.each do |d|%> <%= h.check_box :location_id, {}, d.id %><%= d.name %><br /> <% end %> <% end %> </div> <% end -%> <br /> <%= f.submit t("devise.invitations.new.submit_button"), class: "btn btn-primary btn-block" %> <% end %> EDIT: The error is occurring on _self.resource = invite_resource_ |
PG::ConnectionBad: FATAL: database "db_name" does not exist on EC2 amazon Posted: 12 Jul 2016 06:26 AM PDT I am using capistrano for rails application deployment. But i'm facing PG::ConnectionBad: FATAL: database "db_name" does not exist error. Kindly guide me. |
Issue while deploying Ruby branch for SSHkit Posted: 12 Jul 2016 06:10 AM PDT I was deploying the ROR branch using vagrant machine. It was properly working previously but now since last 4-5 days it is showing error. error is like below: [vagrant@precise64 $] > bundle exec cap qa deploy:check --trace ** Invoke qa (first_time) ** Execute qa ** Invoke load:defaults (first_time) ** Execute load:defaults ** Invoke deploy:check (first_time) ** Execute deploy:check ** Invoke git:check (first_time) ** Invoke git:wrapper (first_time) ** Execute git:wrapper Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text. Enter passphrase for /home/vagrant/.ssh/id_rsa:XXXXXX INFO Uploading /tmp/git-ssh.sh 100.0% INFO [332996a5] Running /usr/bin/env chmod +x /tmp/git-ssh.sh as rails@xx.xx.xx.xx INFO [332996a5] Finished in 0.695 seconds with exit status 0 (successful). ** Execute git:check Please enter branch: |master| cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as rails@xx.xx.xx.xx: exit /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:16:in rescue in block (2 levels) in execute' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:12:in block (2 levels) in execute' SystemExit: exit /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/capistrano-3.0.0/lib/capistrano/tasks/git.rake:21:in exit' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/capistrano-3.0.0/lib/capistrano/tasks/git.rake:21:in block (4 levels) in top (required)' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/backends/abstract.rb:85:in with' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/capistrano-3.0.0/lib/capistrano/tasks/git.rake:20:in block (3 levels) in top (required)' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in instance_exec' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in run' /home/vagrant/.rvm/gems/ruby-1.9.3-p374/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute' Tasks: TOP => git:check As per the above error, issue is somewhere in SSHKit or in task git:check but i am not able to understand the exact cause. someone told me to execute the same using sshkit tracing over cap but i don't know how to do it. can someone help me to resolve this issue and let me know in case you require some more information. |
Rails, Passenger,Nginx my app does not start in the port it should? Posted: 12 Jul 2016 06:05 AM PDT I have my app's nginx config file in /etc/nginx/sites-available/cava which as you can see is set to run on port 5000. server { listen 5000; listen [::]:5000; server_name cava; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/cava/public; try_files $uri/index.html $uri @app; # Add index.php to the list if you are using PHP #index index.html index.htm index.nginx-debian.html; server_name _; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } } After that I have to start my rails server right? So I go into my app's folder and hit rails server -e production -p 5000 But I get an error nginx: [emerg] bind() to 0.0.0.0:5000 failed (98: Address already in use) nginx: [emerg] bind() to 0.0.0.0:5000 failed (98: Address already in use) nginx: [emerg] bind() to 0.0.0.0:5000 failed (98: Address already in use) nginx: [emerg] bind() to 0.0.0.0:5000 failed (98: Address already in use) nginx: [emerg] bind() to 0.0.0.0:5000 failed (98: Address already in use) nginx: [emerg] still could not bind() What do I do wrong? I am a complete beginner with Nginx so I mostly follow guides without knowing exactly what I am doing. Also a side question: Should I add the SSL configuration on my website config and each website config or should I add it in my nginx.config once and for all? |
rails query with distinct doesn't work Posted: 12 Jul 2016 07:21 AM PDT so I think I found a bug in rails. I wanted to do a sql-query with a DISTINCT and a COUNT in one but it doesn't work. My code: Company.joins(users: :orders).joins(users: :logins).select("companies.name, COUNT(DISTINCT orders.time) AS cTime, first_login").group('companies.name') I used "code".to_sql to test it into sqliteman AND IT WORKED. SQL: SELECT companies.name, COUNT(DISTINCT orders.time) AS cTime, first_login FROM "companies" INNER JOIN "users" ON "users"."company_id" = "companies"."id" INNER JOIN "orders" ON "orders"."user_id" = "users"."id" INNER JOIN "logins" ON "logins"."user_id" = "users"."id" GROUP BY companies.name comoany_name / orders / login OUTPUT SQL: test_company / 13 / 2015-02-19 13:33:37.000000 OUTPUT WEBSITE: test_company / 1 / 2015-02-19 13:33:37.000000 There is a different result between the view from rails and sql. greetings |
Masonry with AJAX; infinite scrolling not working (Rails) Posted: 12 Jul 2016 05:32 AM PDT So my index.html.haml inside PostsController goes like this -- by default it renders a partial that shows the posts in normal view, but when clicked on a "Masonry" link on the page, the container containing the posts in normal view hides and a container containing the posts in 'masonry' view gets appended to the same index page via AJAX. Maybe it'll be clearer if you have a look at the files: posts_controller.rb def index @posts = Post.all.paginate(page: params[:page], per_page: 10).order('created_at DESC') respond_to do |format| format.html format.js end end def masonry @posts = Post.all.paginate(page: params[:page], per_page: 10).order('created_at DESC') respond_to do |format| format.html format.js end end index.html.haml = link_to "Masonry", masonry_path, remote: true .postindex = render 'view' _view.html.haml -@posts.each do |post| .image.center-block = link_to (cl_image_tag(post.image_url, width:640, class: "img-responsive")), post_path(post) #infinite-scrolling = will_paginate @posts masonry.html.haml = render 'mason' _mason.html.haml #pins.transitions-enabled.infinite-scroll.page.clearfix -@posts.each do |post| .box = link_to (cl_image_tag(post.image_url, width:640, class: "img-responsive")), post_path(post) #infinite-scrolling = will_paginate @posts I'm using this jQuery plugin for the infinite scrolling. Now, the thing is, the infinite scrolling works fine when I'm redirected to masonry_path (i.e. when I remove remote: true from the link), but it doesn't work when the masonry view is AJAX-ed into index . Take a look at the js files: masonry.js.erb in /views/posts $('.postindex').hide().after('<%= j render("mason") %>'); $('#pins').masonry({ itemSelector: '.box', }); $('#pins').infinitescroll({ navSelector : '.pagination', nextSelector : '.pagination a', itemSelector : '.box', }, function( newElements ) { var $newElems = $( newElements ).css({ opacity: 0 }); $newElems.imagesLoaded(function(){ $newElems.animate({ opacity: 1 }); $('#pins').masonry( 'appended', $newElems, true ); }); $("abbr.timeago").timeago(); }); masonry.js in /javascripts $(document).on('ready page:load', function() { var $container = $('#pins'); $container.css({ opacity: 0 }); $container.imagesLoaded(function(){ $container.animate({ opacity: 1 }); $container.masonry({ itemSelector: '.box', }); }); $container.infinitescroll({ navSelector : '.pagination', nextSelector : '.pagination a', itemSelector : '.box', }, function( newElements ) { var $newElems = $( newElements ).css({ opacity: 0 }); $newElems.imagesLoaded(function(){ $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); }); $("abbr.timeago").timeago(); }); }); I know there's a lot of DRY-ing up to do, but I don't know how to accomplish this in another way. So I'd be glad if you could help me out with that too! Thanks in advance! |
Reload namespaced constant in initializer Posted: 12 Jul 2016 05:14 AM PDT Ran into an interesting scenario today that I'm unsure how to resolve. Given a rails app with an initializer: file: config/initializers/integrations.rb Integrations::CONFIGS = { "key" => "value" }.freeze If I go into bundle exec rails console and ask for that constant it works as expected: Integrations::CONFIGS => {"key"=> "value"} Then if I use reload! in the console, I lose that constant: [2] pry(main)> reload! Reloading... => true [3] pry(main)> Integrations::CONFIGS NameError: uninitialized constant Integrations::CONFIGS from (pry):3:in `<main>' If I remove the namespace and just have CONFIGS as a constant it works and reloads as expected. I've read through as much of the reload! documentation as I could find and from what I can tell this isn't expected. My question being, how can I correctly use a namespaced constant in an initializer while also still being able to use reload! ? |
How to load partial templates as Hash values in Jbuilder Posted: 12 Jul 2016 05:00 AM PDT How to load partial templates as Hash values using Jbuilder? Here I want to do. # _user.jbuilder json.name 'John' # foo.jbuilder foo = { embedded: { user: json.partial!('bar'), }, } json.merge!(foo) # I want Jbuilder to output this JSON... { embedded: { user: { name: "John" } } } But actually, I got JSON like the below. { embedded: { user: "{\n\n}" }, name: "John" } Also I know it's possible to do using json.<keyName> do end (like the below), but I got Hash type. // It's impossible to get Hash type... json.embedded do json.user do json.partial!('bar') end end Because I want to call a method using the Hash as arguments. foo = { embedded: { user: json.partial!('bar'), }, } // Finally, I want to call a method... json.merge!(specific_method(foo)) |
Use activerecord to multiply join the same table (ruby_on_rails) Posted: 12 Jul 2016 04:48 AM PDT My application for learning words by reading the sentences and the translation of these sentences. Each word has and belong to many sentences, each sentence has translate ('links' table). I need to get words (english for example) that have sentences (english) that have sentences (russian) DB: words sentences_words sentences links(sentences_sentences) _______________________ _____________________ __________________ _____________________________ |id |lang |word | |word_id|sentence_id| |id|lang|sentence| |sentence_1_id|sentence_2_id| |1 |rus |Ё | | 1 | 1 | |1 |rus | ЁЖ | | 1 | 5 | |2 |rus |Ж | | 1 | 4 | |2 |rus | ЗЖ | | 1 | 8 | |3 |rus |З | | 2 | 1 | |3 |rus | ЙЫ | | 2 | 6 | |4 |rus |Й | | 2 | 2 | |4 |rus | ЁЗ | | 3 | 7 | |5 |rus |Ы | | 3 | 2 | |5 |eng | ab | | 3 | 10 | |6 |eng |a | | 3 | 4 | |6 |eng | bc | | | | |7 |eng |b | | 4 | 3 | |7 |eng | ca | | | | |8 |eng |c | | 5 | 3 | |8 |jpn | | | | | |9 |jpn | ... | | 6 | 5 | |9 |jpn | | | | | |10 |jpn | ... | | 6 | 7 | |10|jpn | | | | | | | | | | 7 | 5 | |11|jpn | | | | | | | | | | 7 | 6 | |12|jpn | | | | | | | | | | 8 | 6 | |13|jpn | | | | | | | | | | 8 | 7 | |14|jpn | | | | | Models: class Word < ApplicationRecord has_and_belongs_to_many :sentences end class Sentence < ApplicationRecord has_and_belongs_to_many :words has_and_belongs_to_many(:sentences , :join_table => "links", :foreign_key => "sentence_1_id", :association_foreign_key => "sentence_2_id") end This sql works nice but I need activerecord query: sql = " select w.word from words w join sentences_words sw on sw.word_id = w.id join sentences s1 on sw.sentence_id = s1.id join links l on l.sentence_1_id = s1.id join sentences s2 on l.sentence_2_id = s2.id where w.language = 'eng' and s1.language = 'eng' and s2.language = 'rus' group by w.id order by w.id" @words = ActiveRecord::Base.connection.execute(sql) Thank you! |
Check if number is NaN in Ruby on Rails Posted: 12 Jul 2016 04:40 AM PDT I'm trying to check if a variable I have is equals to NaN in my Ruby on Rails application. I saw this answer, but it's not really useful because in my code I want to return 0 if the variable is NaN and the value otherwise: return (average.nan ? 0 : average.round(1)) The problem is that if the number is not a NaN I get this error: NoMethodError: undefined method `nan?' for 10:Fixnum I can't check if the number is a Float instance because it is in both cases (probably, I'm calculating an average). What can I do? It is strange only to me that a function to check if a variable is equals to NaN is avaible only to NaN objects? |
Turbolinks not rendering code on page change Posted: 12 Jul 2016 04:17 AM PDT I'm using Segment.io to do tracking on my site. We have a live chat widget that I'd like to be displayed on every page. However I'm unable to figure out how to make this work. I've created an analytics.js which loads in the body (I've also tried adding the analytics.page(); to the body without any results): window.analytics = window.analytics || []; window.analytics.methods = ['identify', 'group', 'track', 'page', 'pageview', 'alias', 'ready', 'on', 'once', 'off', 'trackLink', 'trackForm', 'trackClick', 'trackSubmit']; window.analytics.factory = function(method){ return function(){ var args = Array.prototype.slice.call(arguments); args.unshift(method); window.analytics.push(args); return window.analytics; }; }; for (var i = 0; i < window.analytics.methods.length; i++) { var key = window.analytics.methods[i]; window.analytics[key] = window.analytics.factory(key); } window.analytics.load = function(key){ if (document.getElementById('analytics-js')) return; var script = document.createElement('script'); script.type = 'text/javascript'; script.id = 'analytics-js'; script.async = true; script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'cdn.segment.io/analytics.js/v1/' + key + '/analytics.min.js'; var first = document.getElementsByTagName('script')[0]; first.parentNode.insertBefore(script, first); }; window.analytics.SNIPPET_VERSION = '3.1.0'; window.analytics.load('kYDWuP6nxI'); window.analytics.page(); document.addEventListener("turbolinks:load", function() { console.log('page change'); analytics.page(); }); When I visit a new page on the app it shows the console log, but analytics.page(); doesn't seem to be rendered except when I do a manual page refresh. Anybody know how to fix this? |
Issue related to import excel file in rails Posted: 12 Jul 2016 04:22 AM PDT I am following Ryan Bates railscast website as tutorial for importing an excel file into my rails application. And finally I have done it. Now I want to perform a bit more complex operations with this excel data. I am able to import the whole content of the excel file into the database table. But now I want to get each row of the excel file before inserting into database. I need to perform operations on each row of excel file. I don't know how to achieve this. My model name is Employee and so my table name is employees. Now my model is:- class Employee < ActiveRecord::Base def self.import(file) spreadsheet= Employee.open_spreadsheet(file) header=spreadsheet.row(1) (2..spreadsheet.last_row).each do |i| row=Hash[[header,spreadsheet.row(i)].transpose] em=find_by_id(row["id"])||new em.attributes=row.to_hash.slice('firstname') em.save end end def self.open_spreadsheet(file) case File.extname(file.original_filename) #when ".csv" then Roo::Csv.new (file.path nil, :ignore) when ".xlsx" then Roo::Excelx.new (file.path) #when ".xlsx" then Excelx.new (file.path, nil, :ignore) else raise "Unknown file type: #{file.original_filename}" end end end Another problem is that I want to pass the content of the row to controller, but I know that in MVC architecture I should not pass model data to controller. Then tell me is there any way out? |
Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
ReplyDeleteruby on rails training
ruby on rails training India
ruby on rails training Hyderabad