Using JS in Rails Views Posted: 10 Mar 2016 07:38 AM PST I have a loop of articles , which each have one comment presented. The goal is to present that one comment dynamically/asynchronously using JS. My question is: How do I call/activate the logic I've defined below? #welcome/index.haml - @articles.each do |article| = article.title - article.comments.each do |comment| %comment-content{ :id => "comment-#{comment.id}" } #welcome.js // var var comment = "#comment-<%= params[:comment_id] %>" // render $(comment).html("<%=j render 'comment_content' %>") #welcome/_comment_content.haml = comment.content |
Rails - after_update :reload_page does not refresh the page when record in the database was updated Posted: 10 Mar 2016 07:38 AM PST Here is my controller (ClientController): class ClientController < ApplicationController layout 'application' before_filter :client_selected, :only => [ :index,:show] after_filter :reload_page, :only => :update def reload_page respond_to do |format| format.html {redirect_to :controller=>"client", :action=>"show", :layout => 'application'} format.js {render inline: "location.reload();" } end def index end def show end end Don't know what I am missing here? |
bundle install results in "mapping values are not allowed in this context" error Posted: 10 Mar 2016 07:38 AM PST I have a rails 4 project that has been working for some time. I attempted to install taps but got an error message: $ gem install taps /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/psych.rb:370:in `parse': (<unknown>): mapping values are not allowed in this context at line 2 column 29 (Psych::SyntaxError) from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/psych.rb:370:in `parse_stream' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/psych.rb:318:in `parse' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/psych.rb:245:in `load' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/config_file.rb:333:in `load_file' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/config_file.rb:198:in `initialize' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/gem_runner.rb:74:in `new' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/gem_runner.rb:74:in `do_configuration' from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/gem_runner.rb:39:in `run' from /usr/local/rvm/rubies/ruby-2.2.1/bin/gem:21:in `<main>' I get the same error message when trying to run gem list or bundle update . I searched for similar problems, and it seems the cause is typically an improperly formatted YAML file. My database.yml file and Gemfile were not recently updated, so I don't know when this bug was introduced. I found a rails issue on Github that describes this error, and someone recommended parsing YAML files with irb to isolate the issue. I tried parsing database.yml and Gemfile : config/database.yml # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 production: <<: *default database: db/production.sqlite3 $ irb -ryaml 2.2.1 :001 > YAML.load_file 'config/database.yml' => {"default"=>{"adapter"=>"sqlite3", "pool"=>5, "timeout"=>5000}, "development"=>{"adapter"=>"sqlite3", "pool"=>5, "timeout"=>5000, "database"=>"db/development.sqlite3"}, "test"=>{"adapter"=>"sqlite3", "pool"=>5, "timeout"=>5000, "database"=>"db/test.sqlite3"}, "production"=>{"adapter"=>"sqlite3", "pool"=>5, "timeout"=>5000, "database"=>"db/production.sqlite3"}} Gemfile source 'https://rubygems.org' gem 'rails', '4.2.2' gem 'faker', '1.4.2' gem 'will_paginate', '3.0.7' gem 'bootstrap-will_paginate', '0.0.10' gem 'bootstrap-sass', '3.2.0.0' gem 'sass-rails', '5.0.2' gem 'uglifier', '2.5.3' gem 'coffee-rails', '4.1.0' gem 'jquery-rails', '4.0.3' gem 'turbolinks', '2.3.0' gem 'jbuilder', '2.2.3' gem 'devise', '3.5.6' group :development, :test do gem 'sqlite3', '1.3.9' gem 'byebug', '3.4.0' gem 'web-console', '2.0.0.beta3' gem 'spring', '1.1.3' end group :test do gem 'minitest-reporters', '1.0.5' gem 'mini_backtrace', '0.1.3' gem 'guard-minitest', '2.3.1' end group :production do gem 'pg', '0.17.1' gem 'rails_12factor', '0.0.2' end $ irb -ryaml 2.2.1 :001 > YAML.load_file 'Gemfile' => "source 'https://rubygems.org'\n\ngem 'rails', '4.2.2' gem 'faker', '1.4.2' gem 'will_paginate', '3.0.7' gem 'bootstrap-will_paginate', '0.0.10' gem 'bootstrap-sass', '3.2.0.0' gem 'sass-rails', '5.0.2' gem 'uglifier', '2.5.3' gem 'coffee-rails', '4.1.0' gem 'jquery-rails', '4.0.3' gem 'turbolinks', '2.3.0' gem 'jbuilder', '2.2.3' gem 'devise', '3.5.6'\ngroup :development, :test do gem 'sqlite3', '1.3.9' gem 'byebug', '3.4.0' gem 'web-console', '2.0.0.beta3' gem 'spring', '1.1.3' end\ngroup :test do gem 'minitest-reporters', '1.0.5' gem 'mini_backtrace', '0.1.3' gem 'guard-minitest', '2.3.1' end\ngroup :production do gem 'pg', '0.17.1' gem 'rails_12factor', '0.0.2' end" Both files parse correctly, so I am stuck. I don't know why the commands keep failing since the error message doesn't identify the offending file. |
Devise/OmniAuth Override default callback url Posted: 10 Mar 2016 07:33 AM PST I'm using Devise 3.5 with Omniauth in a Rails 4 app. I've created an integration with Facebook that allows a user to connect their Facebook account to my app. Currently when the user clicks the connect button, they're sent to /user/auth/facebook and then redirected to the callback url that Omniauth generates: /user/auth/facebook/callback . What I'd like to do is manually override this callback url in some cases - meaning that I don't want to override it in an initializer - with a fully qualified url. For example, if a user starts out on http://www.example.com/ I might want to override the default callback url with http://app.example.com/user/auth/facebook/callback . My app has dynamic subdomains and a user will (almost) always begin the authentication process on a subdomain. Unfortunately it seems that Facebook doesn't support wildcards in oauth redirect urls, which is why I want the ability to detect if a user is on a subdomain and adjust the callback url to something that I have whitelisted on my Facebook app so that the authorization process succeeds. From what I've read, the url helper omniauth_authorize_path accepts additional arguments to be passed on as parameters. I've tried passing a custom callback path in like so, but without success: user_omniauth_authorize_path(:facebook, callback_path: @custom_callback) I've also tried changing callback_path to redirect_url and redirect_uri , but nothing seems to work. When I look at the link that's generated, it does indeed include the callback as a parameter in the url, but when I click the link, I'm redirected back to the default callback url instead of the custom callback url. |
column must appear in the GROUP BY clause or be used in an aggregate function Ruby Posted: 10 Mar 2016 07:33 AM PST As I was using Chartkick to install some graphs into my ruby on rails project I am running into a strange error which I cannot resolve or understand other explanations. The following code I embedded into my view file. <%= area_chart @bets_by_month.group_by_day(:date_of_bet).sum(:profit_or_loss) %> the @bets_by_month instance is declared in the controller like this @bets_by_year = Bet.where("EXTRACT(YEAR FROM date_of_bet) = ?", params[:year]) @bets_by_month = @bets_by_year.where("EXTRACT(MONTH FROM date_of_bet) = ?", params[:month]) @bets_by_month = @bets_by_month.order("date_of_bet DESC") Which is returning error when I try to load the page. PG::GroupingError: ERROR: column "bets.date_of_bet" must appear in the GROUP BY clause or be used in an aggregate function However when I embed this code into my view file I get no problems. <%= area_chart Bet.group_by_day(:date_of_bet).sum(:profit_or_loss) %> The reason I need to use the instance is because I want each month to have a different graph displaying the results from that month. |
How to call an active_model_serializer to serialize records explicitly Posted: 10 Mar 2016 07:32 AM PST I have a serializer for a TimeEntry model that looks like this: class TimeEntrySerializer < ActiveModel::Serializer attributes :id, :description, :duration has_one :project end And It works as expected when I just return all the records: def index @time_entries = current_user.time_entries.all respond_to do |format| format.html format.json { render json: @time_entries } end end However, I want to return the entries organized by day, something like this: [ { "2016-03-16" => [TimeEntry1, TimeEntry2, TimeEntry3] }, { "2016-03-17" => [TimeEntry1, TimeEntry2] } ] I do it like this form my model: def self.get_entries_for_user(current_user) current_user.time_entries .group_by { |item| item.created_at.to_date.to_s } .map { |day, entries| { day => entries } } end But now, the serializer is not working for the TimeEntry object, I'm not quite sure if it's actually supposed to work in this situation... I want to avoid having to format the data myself: def self.get_entries_for_user(current_user) current_user.time_entries .group_by { |item| item.created_at.to_date.to_s } .map do |day, entries| { day => entries.map do |entry| { :id => entry.id, :description => entry.description, :duration => entry.duration_ms, :start_time => entry.time.begin, :end_time => entry.time.end, :project_id => entry.project.id } end } end end Is it possible to use the active_model_serializer for this situation? If not possible, how can I format the data more efficiently an avoid the nested map calls? |
Read a textfile (GAMS Output) into my database Posted: 10 Mar 2016 07:31 AM PST I've got a textfile which is a GAMS Outputfile and I want to read it into my database, but unfortunately this doesn't work. Textfile: I need the 4th column of this file, these values are my xij. Here is the code in the controller: I am using the SQLite Browser for my database, but I have no idea why the column for xij is empty. Especially because it is working for y with the same commands and the textfile for y has the same structure as the one for x. Does anyone have an idea what could fix my problem? Many thanks in advance! |
Cannot authorize a nested route using Spree and Cancan Posted: 10 Mar 2016 07:17 AM PST I'm using Spree with cancan to give authorization to a user with limited access. My problem is that I have a nested route and I can't seem to get to the nested one. In my routes.rb resources :users do get :ensembler_looks end My ability.rb if user.respond_to?(:has_spree_role?) && user.has_spree_role?('stylist') can :manage, User can :manage, EnsemblerLook, :user => { :user_id => user.id } #not sure if needed can :manage, Product end In my controllers I've tried a mix of: My user_controller_decorator.rb module Admin UsersController.class_eval do load_and_authorize_resource :ensemblerlook load_and_authorize_resource :user, :through => :ensemblerlook, :shallow => true and In ensembler_looks_controller.rb module Admin class EnsemblerLooksController < ResourceController # load_and_authorize_resource :user # load_and_authorize_resource :ensemblerlook, :through => :user, :shallow => true So far, I still get authorization failures. Any help would be greatly appreciated. |
NoMethodError in StaticPages#home rails tutorial Michael Hartl chapter 5.1 Posted: 10 Mar 2016 07:31 AM PST I am having trouble with Chapter 5, Section 1. I'm supposed to see a (dead) link on the home page, when I insert the code, but instead I get an error. |
varying header elements that are yield in the layout folder in rails 4.2.4 Posted: 10 Mar 2016 07:16 AM PST I am newish to programming and building my first e-commerce web application using rails 4.2.4 I have a price container in the header of my application.html.erb which yields across the show.html.erb and index.html.erb pages. Issue: I only want the price container to yield on the show page (NOT the index). I have tried deleting the <% content_for :head do %> on the index page but the price container remains on this specific page. I would be grateful for some steering. Screenshots and code below. My application.html.erb page <!DOCTYPE html> <html lang="en"> <head> <title>One Month Growth Hacking</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, user-scalable=no"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,300,800"> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => false %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => false %> <%= csrf_meta_tags %> </head> <body> <div id="content" class="container"> <header id="content-header"> <div id="price-container"> <span class="glyphicon glyphicon-tag"></span><span class="price">$4.99</span> </div> <%= yield :head %> </header> <%= yield %> </div> My index.html.erb page <% content_for :head do %> <%= image_tag('skincare.png', id: 'content-header-img', alt: 'check out our products') %> <% end %> <section id="article-title" class="row clearfix"> <article id="details-article"> <h1 id="article-title">Nippon Beauty Products</h1> </article> </section> <section id="products"> <% @products.each do |product| %> <div class="product clearfix"> <a href="<%=product_path(product) %>"</a> <div class="product-image-container"> <img src="<%= asset_path product.thumbnail_image_name %>" alt="<%= product.title %>"/> <span class="product-price">$<%= product.price %></span> </div> <p class="product-title"><%= product.title %></p></a> </div> <% end %> </section> |
Response Headers not setting Ruby on rails Posted: 10 Mar 2016 07:03 AM PST I'm using devise for authentication . and i want to set some custom response and request headers . I'm trying to do response.headers['HEADER NAME'] = 'HEADER VALUE' but it's not setting . Can anyone help . plus i want to get / set request and response headers in every request |
Needing the same ID for two different entries in one tablerow Posted: 10 Mar 2016 06:45 AM PST I built an app that solves a railway optimization problem. You can create some stations which you'll need to create a timetable with a trainnumber, arrival station, arrival time, departure station, departure time and the demand for this railconnection. Now i got the problem, that I have only one station_id which is used for the departure station but I need the station_id for my arrival station too. This is essential because when I delete a station I want that the correspondending railconnection using this station to be deleted too. This is the views/timetables/_form <% provide(:title, 'Fahrplan') %> <%= form_for(@timetable) do |f| %> <% if @timetable.errors.any? %> <div id="error_explanation"> <h2><%= @timetable.errors.count %> Fehler ! Da ist wohl etwas schief gelaufen:</h2> <ul> <% @timetable.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label 'Zugnummer' %><br /> <%= f.text_field :train_number, required: "required" %> </div> <div class="field"> <%= f.label 'Startbahnhof' %><br /> <%= f.collection_select :station_id, Station.all, :id, :name, {:include_blank => "Bitte auswählen"} %> </div> <div class="field"> <%= f.label :departure_time, 'Abfahrt' %><br /> <%= f.text_field :departure_time, type: "text", pattern:"[0-9]{4,4}",title:"hhmm", required: "required" %> </div> <div class="field"> <%= f.label 'Zielbahnhof' %><br /> <%= f.collection_select :arrival_station, Station.all, :shortcut, :name, {:include_blank => "Bitte auswählen"} %> </div> <div class="field"> <%= f.label :arrival_time, 'Ankunft' %><br /> <%= f.text_field :arrival_time, type: "text", pattern:"[0-9]{4,4}",title:"hhmm", required: "required" %> </div> <div class="field"> <%= f.label :demand_first_class, 'Nachfrage 1. Klasse' %><br /> <%= f.text_field :demand_first_class, required: "required" %> </div> <div class="field"> <%= f.label :demand_second_class, 'Nachfrage 2. Klasse' %><br /> <%= f.text_field :demand_second_class, required: "required" %> </div> <div class="actions"> <%= f.submit 'Fahrplan und Nachfrage anlegen oder aktualisieren' %> </div> Is there a command that creates, when creating a new station, e.g. a station_departure_id that has allways the same id number as the station_id? Are there other possibilities to solve this issue? |
Rails 4 - threading error Posted: 10 Mar 2016 07:39 AM PST I am trying to perform some calculations to populate some historic data in the database. The database is SQL Server. The server is tomcat (using JRuby). I am running the script file in a rails console pointed to the uat environment. I am trying to use threads to speed up the execution. The idea being that each thread would take an object and run the calculations for it, and save the calculated values back to the database. Problem: I keep getting this error: ActiveRecord::ConnectionTimeoutError (could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)) code: require 'thread' threads = [] items_to_calculate = Item.where("id < 11").to_a #testing only 10 items for now for item in items_to_calculate threads << Thread.new(item) { |myitem| my_calculator = ItemsCalculator.new(myitem) to_save = my_calculator.calculate_details to_save.each do |dt| dt.save! end } end threads.each { |aThread| aThread.join } |
ActiveRecord::InvalidForeignKey Error Posted: 10 Mar 2016 07:18 AM PST I have 5 models, student, company, job, and accept, apply. So, I want the company to accept the student who have been applied to the job. I have managed the applying process, the student can now apply to many jobs. However, I have problem with the accepting process. Here is what I have so far: # student.rb has_many :applies has_many :jobs, through: :applies has_many :accepts # company.rb has_many :jobs has_many :applies, through: :jobs has_many :accepts # job.rb belongs_to :company has_many :applies has_many :students, through: :applies has_many :accepts # accept.rb belongs_to :student belongs_to :company belongs_to :job # apply.rb belongs_to :student belongs_to :job has_many :accepts I created a controller: #accepts_controller.rb class def create @accept = current_company.accepts.create(accept_params) flash[:success] = "Your candidate has been accepted!" redirect_to @accept.student end private def accept_params params.require(:accept).permit(:student_id, :job_id, :company_id, :apply_id) end I create this routes so the company can run the accepts within the student profile page (students#show): # routes.rb resources :students do resources :accepts, only: [:create] end I added these code to the student profile page: # views/students/show.html.erb <% if current_company %> <% if @student.jobs(params[:id]) %> <div class="row text-center"> <%= render 'accepts/form' %> </div> <% end %> <% end %> I created a partial form: # views/accepts/_form.html.erb <%= simple_form_for([@student, @student.accepts.new]) do |f| %> <%= f.hidden_field :student_id, value: @student.id %> <%= f.hidden_field :job_id, value: @student.jobs %> <%= f.hidden_field :apply_id, value: @student.applies %> <%= f.button :submit, class: 'btn btn-success' %> <% end %> Then I open the student profile who have been applying. Everything's look good but when I tried to click the Accept button. Here is what I got: ActiveRecord::InvalidForeignKey in AcceptsController#create PG::ForeignKeyViolation: ERROR: insert or update on table "accepts" violates foreign key constraint "fk_rails_e10b9d1e41" DETAIL: Key (job_id)=(0) is not present in table "jobs". : INSERT INTO "accepts" ("student_id", "job_id", "company_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" I believe it won't read which job_id and apply_id that should be added since the student has many jobs and also applies. What should I do then? Update 1 I opened rails console and type this command: > Accept.all => [#<Accept id: 1, student_id: 3, company_id: 1, job_id: nil, apply_id: nil, created_at: "2016-03-10 13:59:22", updated_at: "2016-03-10 14:11:36">] As you see, it won't pass the job_id and appy_id as it should be. Update 2 Here is the process, when the student applied, the company will see the list of the applicants on the companies#your_applicant: #companies_controller.rb def your_applicant @applicants = current_company.applies end And here is the view: <% @applicants.each do |applicant| %> <%= link_to applicant.student do %> <%= applicant.student.full_name %> as <%= applicant.job.job_title %><br> <% end %> <% end %> Currently, it will list all the applicants and when the company click the link, they will be redirected to the user show page. Is there any way to get the apply_id and job_id from the your_applicant view and pass it to the url of the profile show page, so it will look something like this: http://localhost:3000/students/1?job_id=3&apply_id=1 So then, when the company click the accept button in the user show page, it will grab the job_id and the apply_id from the url. Is that possible? Just guessing. |
User - Feedback Implementation - Create action Posted: 10 Mar 2016 06:54 AM PST I have implemented the following user.rb has_many :authored_feedbacks, :class_name => "Feedback", :foreign_key => "author_id", :dependent => :destroy has_many :received_feedbacks, -> { order("id DESC")}, :class_name => "Feedback", :foreign_key => "recipient_id", :dependent => :destroy feedback.rb belongs_to :author, :foreign_key => :author_id, :class_name => "User" belongs_to :recipient, :foreign_key => :recipient_id, :class_name => "User" belongs_to :listing feedbacks_controller.rb def new @author = current_user @listing = Listing.find(params[:listing_id]) @recipient = @listing.user @feedback = Feedback.new @feedback_presenter = FeedbackPresenter.new(@listing) end def create @author = current_user @listing = Listing.find(params[:listing_id]) @recipient = @listing.user @feedback = @author.authored_feedbacks.build(listing_id: @listing.id, author_id: @author.id, recipient_id: @recipient.id, rating: params[:feedback][:rating], comment: params[:feedback][:comment]) if @feedback.save flash[:notices] = ["Feedback successfully submitted"] redirect_to user_feedbacks_path(@user) else render 'new' end end private def feedback_params params.require(:feedback).permit! (just ensure it's not a whitelist issue) end from listings/show.html.erb I link to create a new Feedback: <%= link_to 'Leave feedback for this user', new_user_feedback_path(@user, @feedback, listing_id: @listing.id, author_id: current_user.id, recipient_id: @listing.user.id) %> feedbacks/new.html.erb <%= form_for [@author, @feedback], url: user_feedbacks_path(@author, @feedback) do |f| %> <%= f.label :rating %> <%= f.select(:rating, @feedback_presenter.feedback_options, {}, id: 'rating', class: 'form-control') %> <%= f.label :comment %> <%= f.text_field :comment, class: "form-control" %> <%= f.submit "Submit Feedback", class: "btn btn-primary" %> <% end %> I am happy with the association setup and believe I am passing all the required params but as it stands I creating any feedback records. I am unsure where I am going wrong here so wanted to ask here on SO. Edit - Added server output: Started POST "/users/5/feedbacks" for ::1 at 2016-03-10 22:53:02 +0800 Processing by FeedbacksController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"48PdNPwx3Dbusm+4H7n87+PvUFRCJUTxLAfiaMwxvAxFQww6YVUn3j5fChwGhwqHSc0ARuo+i5h+p8QvC8vw+A==", "feedback"=>{"rating"=>"Positive", "comment"=>"312435"}, "commit"=>"Submit Feedback", "user_id"=>"5"} Listing Load (0.2ms) SELECT "listings".* FROM "listings" WHERE "listings"."id" = $1 LIMIT 1 [["id", nil]] Redirected to http://localhost:3000/users/1/feedbacks/new?listing_id=5&recipient_id=1 Completed 302 Found in 3ms (ActiveRecord: 0.2ms) |
rails cancancan gem how to limit permission Posted: 10 Mar 2016 06:44 AM PST I want to use cancancan restrict the permission. For example: If I have a Task model. User only can see not assigned tasks, cannot see assigned tasks. Ability model: can :manage, Task, :user_id => false But right now, user cannot see all the tasks. What is wrong? Hope anyone can help me! Thanks in advance! |
Rails add array field to params.permit Posted: 10 Mar 2016 06:56 AM PST EDIT to reflect current answers and nested_attributes I have the following models and controller reservation.rb has_many :taxes, through: :tax_requests has_many :tax_requests, dependent: :destroy accepts_nested_attributes_for :taxes reservation_controller.rb def reservation_params params.require(:reservation).permit( :start_date, :end_date, :status, :tag_list, :sales_channel_id, :comments, :room_category_id, :client_id, tax_attributes: [:id, :name, :value, :abbreviation, :hotel_id]) end tax.rb has_many :reservations, through: :tax_requests has_many :tax_requests validates :name, :value, :abbreviation, presence: true tax_request.rb belongs_to :reservation belongs_to :tax And in the reservation form view(for reservation creation) = f.select :taxes, options_from_collection_for_select(Tax.all, :id, :abbreviation, @reservation.taxes), {}, multiple: true But, when accesing reservation_params , I get all the params listed before, except for the :taxes param. If I do params[:reservation] it does appear. If I add taxes: [] to the permit, they do appear, but I get an error, that it is expecting a [Tax] when it actually is getting a [String] |
Where and how to set form for nested resources in rails? Posted: 10 Mar 2016 06:17 AM PST I have an Idea model, which has one Chat , and of course, this chat has messages. Based on the following routes, I want to create a form in the chat page to post messages. # Chat belongs_to :idea, and Chat has_many :chat_messages # I wan't to post messages to /idea/:id/chat/chat_messages resources :ideas do resource :chat, only: :show do resources :chat_messages, only: :create end end For now, my form is in app/views/chats/show.html.erb and looks like that : # @chat and @chat_message are defined in Chat controller but I put them here so you can see them @chat = Chat.where(idea_id: params[:idea_id]).first @chat_message = ChatMessage.new(chat: @chat) <%= form_for [@chat.idea, @chat, @chat_message] do |f| %> <%= f.text_area :body, size: "60x12" %> <%= f.submit "Message" %> <% end %> The form generates the following html (I have removed the inputs and some content which was not relevant) : <form action="/ideas/1/chat/chat_messages.1" accept-charset="UTF-8" method="post"> </form> Why is there .1 in my form action ? (it causes error). How should it be ? i need it to access /ideas/1/chat/chat_messages |
multipleselect is forgeting selected values after proceed Posted: 10 Mar 2016 07:20 AM PST Multiplyselect is forgetting owners values after searching. After proceed i got params[:search] and params[:owners] but only input for search is filled-in. This is my code. def index @all_owners = Owner.select('distinct name').pluck(:name) @animal = Animal.search(params[:search]) @animal = @animals.joins(:owners).where("owners.name IN (?) ", params[:owners].present? ? params[:owners] : @owners) end #------------------------------------------ <%= form_tag animals_path, :method => 'get' do %> <%= text_field_tag :search, params[:search]%> <%= select_tag :owners, options_for_select(@all_owners),id: "multiselect-id", multiple: true %> <%= submit_tag "Search", :name => nil %> <% end %> <% @aminals.each do |animal| %> <%= animal.name %> <%= animal.owners.map(&:name).join(', ') %> <% end %> <script type="text/javascript"> $(document).ready(function() { $('#multiselect-id').select2(); }); </script> |
Ruby on Rails Migration Convert From String To Decimal Posted: 10 Mar 2016 06:25 AM PST I've made a database and already inputted about 30-40 entries into the database but there was a mistake and I have accidentally set some columns of the database to be strings when I need them to be decimals in order to perform operations on them. In order to change the database I have generated a migration file that includes this. class ChangeOddsAndUnitsColumn < ActiveRecord::Migration def change change_column :bets, :units_placed, :decimal change_column :bets, :odds, :decimal end end However when I run rake db:migrate I get the following error PG::DatatypeMismatch: ERROR: column "units_placed" cannot be cast automatically to type numeric The values in each column are already decimal numbers but I can't figure out how to convert them to the decimal type from a string. |
Inсorrect syntax code for pass command line arguments to a rake task Posted: 10 Mar 2016 06:04 AM PST namespace :mails do desc "Send emails" task :send_emails => :environment do User.not_deleted.find_each do |user| Notifier.confirm_about_paid_access(user.id).deliver end end desc "Free subscription for users registered in 2011" task :free_subscription_for => :environment, :year do |t, args| year = args[:year] users = User::registered_in(year) end end displaying error: lib/tasks/mails.rake:10: syntax error, unexpected keyword_do_block, expecting => task :free_subscription_for => :environment, :year do |t, args| What is incorrect in syntax code? |
Ruby On Rails - best way to implement Tinder behavior Posted: 10 Mar 2016 06:43 AM PST I am building a Rails Api for a mobile client that works almost the same way as Tinder. The mobile users will receive some images and will like, dislike or give a neutral mark to the image. I'd like to know what is the best way to implement such a system knowing that if user X receives an image Y(then gave it a like, a dislike or a neutral mark), how to make sure he/she won't receive the same image. I am looking for a powerful technique or model that will enhance my server performances. FYI, I currently have 10K users and 100K images. so it is very important to make sur performance stay quiet good. I am using Ruby-on-Rails 4 and Postgresql. |
Devise, STI, why not signed in after sign up? Posted: 10 Mar 2016 06:15 AM PST I'm new to Rails and practicing. I first tried having two Devise models for my users, it was easy to get but not very DRY. I'm now trying STI with Devise Users but I have problems with routes. 1- When a user signs up, it's not automatically signed in afterward. 2- When a users tries to access a page where signin in is required, he is redirected to the root page, not to the sign in page. Where do these behaviour come from? My setup: class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end class Admin < User end class Buyer < User end class Seller < User end routes.rb devise_for :users, skip: :registrations devise_for :admins, skip: [:sessions, :registrations] devise_for :sellers, only: :registrations devise_for :buyers, only: :registrations |
Rails error: No HTTP_REFERER was set in the request to this action Posted: 10 Mar 2016 05:58 AM PST I am developing a new rails app. but found a error: ActionController::RedirectBackError in UsersController#show No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"]. my code: rescue_from CanCan::AccessDenied do |exception| redirect_to :back end I have some question for this error: - what is HTTP_REFERER?
- why redirect to back will trigger this error?
Anyone has good idea? |
Selecting distinct datetimes Posted: 10 Mar 2016 07:40 AM PST I'm currently learning how to use Ruby on Rails with The Odin Project and right now I'm tackling making forms. I'm trying to pull unique dates from my database to populate a dropdown options box for a project. The idea is that only dates that are in the database should show up in the options. My problem is duplicate dates keep showing up e.g. 03/03/2016 03/03/2016 04/03/2016 05/03/2016 06/03/2016 06/03/2016 Using find_by_sql I tried SELECT DISTINCT start FROM flights to no avail. After a quick Google search I tried SELECT start FROM flights GROUP BY start but I'm still getting duplicates. I'm not the best with SQL so any help would be appreciated. edit: My datatime column does have a time component so that's probably the issue From the db schema here is my flights table if it's any help create_table "flights", force: :cascade do |t| t.integer "from_airport_id" t.integer "to_airport_id" t.datetime "start" t.integer "flight_duration" t.datetime "created_at", null: false t.datetime "updated_at", null: false end |
Access-Token not set in Devise Posted: 10 Mar 2016 05:11 AM PST I'm registering new user using the below function sign_in (user) in which sign_in is Devise function . Devise is setting all the headers except Access-Token , client , Uid and Token-Type Below is my complete code def fb_user_info access_token = params[:accessToken] response = HTTParty.get('https://graph.facebook.com/v2.5/me?fields=email,picture{url},name&access_token='+ access_token) data_json = response.parsed_response data_json = JSON.parse(data_json) if data_json.instance_of? String auth_array = Hash.new auth_array[:uid] = data_json['id'] auth_array[:provider] = 'Facebook' auth_array[:username] = data_json['name'] auth_array[:image] = data_json['picture']['data']['url'] auth_array[:email] = data_json['email'] auth_array[:password] = '123456789' user = User.find_by_uid(data_json["id"]) if user.nil? user = User.new(auth_array) if user.valid? user.save! end sign_in (user) end render json: { data: user} end |
Rails 4 - Writing a unit test for a method that contains config values Posted: 10 Mar 2016 05:07 AM PST I'm just getting started with writing some unit tests in Rails and one of the problems I've ran into is how I should go about testing a method that contains configuration data. The config.yml drink_category_defaults: 1: #beer brand_id: 103 # 4.5% volume_id: 5 # Pint price: 300 2: #wine brand_id: 207 # 12% volume_id: 16 # Medium glass (175ml) price: 300 3: #cider brand_id: 304 # 4.5% volume_id: 12 # Pint price: 300 4: #spirits brand_id: 406 # 40% volume_id: 31 # Large single (35ml) price: 250 5: #alcopops brand_id: 502 # 4.5% volume_id: 52 # Standard bottle (275ml) price: 250 6: #champagne brand_id: 607 # 12% volume_id: 20 # Flute (150ml) price: 400 Method: def self.new_with_defaults_for_category category_id drink = Drink.new category_defaults = APP_CONFIG['drink_category_defaults'][category_id.to_i] if category_defaults drink.drink_category_id = category_id drink.drink_brand_id = category_defaults['brand_id'] drink.drink_volume_id = category_defaults['volume_id'] drink.cost_per_drink = category_defaults['price'] end drink end And the test I currently have: # self.new_with_defaults_for_category test "should return a new drink object with category defaults" do 6.times do |i| i += 1 drink = Drink.new_with_defaults_for_category(i) assert_instance_of(Drink, drink) assert drink.drink_category_id === i assert drink.drink_brand_id.present? assert drink.drink_volume_id.present? assert drink.cost_per_drink.present? end end I feel like I'm going about this in the wrong way. I probably shouldn't be using real config data, and that it should be mocked up for the test in some way. As well as that, just checking that the property is present isn't sufficient, and the test needs to be as specific as possible by checking the actual property values. Would love some opinions on the best way to approach this, thanks a lot. |
Rake: load info about assests into DB Posted: 10 Mar 2016 05:05 AM PST I have dozens of images inside my assets folder. Also I have a picture model, I want to generate url links for each of the image and load it into db. How do I do that with rake task? |
After pre-compile rails assets doesn't work as they should Posted: 10 Mar 2016 05:03 AM PST I faced problem that when I deploy my code to the server with capistrano after pre-compile javascript assets doesn't work as it should. Somehow I have that $(..).bootstraSwither is not a function or for example jQuery fucntion .radio is also not a function. Previous everything worked fine and maybe I managed to changed something and it broke whole stuff. Here is my application.js (i did not touched it): // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery-1.10.1.min //= require jquery-ui-1.10.3.custom.min //= require jquery.ui.touch-punch.min //= require jquery.mobile.custom.min //= require jquery.placeholder //= require jquery.stacktable //= require jquery.tagsinput //= require jquery_ujs //= require jquery.validate.min //= require jquery.cropit //= require bootstrap.min //= require bootstrap-select //= require bootstrap-switch //= require bootstrap-wysiwyg //= require jquery.hotkeys //= require bootbox.min //= require flatui-application //= require flatui-checkbox //= require flatui-radio //= require raphael-2.1.0-min //= require raphael_colorwheel //= require underscore-min //= require knockout-3.2.0 //= require jquery.multiple.select //= require hopscotch.min //= require dropzone //= require sweetalert2.min // //= require global_scripts //= require loader_script //= require toolbar //= require_tree ./newmagazine //= require_tree . Maybe someone have idea what can cause that? Maybe I changed some config files or something like that. Here is my production.rb environment file: FBMagazineDev::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = true config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = true # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) config.log_level = :warn # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) config.assets.precompile += %w( documents.css external.css wireframe1280generate.css wireframe1280welcome.css ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 #config.after_initialize do # require "prawn" # end end I am willing to find here someone who can help me with that issue. |
Ruby on rails. Update results/view with data from JSON. Posted: 10 Mar 2016 05:10 AM PST I am trying to dynamically update search results on my index page by moving the map. The search results should only show the results that are in the map bounds. I can successfully return the bounds to the controller, and my server shows the updated results, I.E, displays only the results within these bounds, but I'm not sure how to reflect/update these results in the view. I feel that I am missing something stupid, but after spending hours on this, I can't see it. So far I have; Gmaps callback: google.maps.event.addListener(handler.getMap(), 'idle', function() { var bounds = handler.getMap().getBounds(); drawItems(bounds); Jquery for bounds : function drawItems(theBounds) { var url = 'gigs.json/?sw_y=' + theBounds.getSouthWest().lng() + '&sw_x=' + theBounds.getSouthWest().lat() + '&ne_y=' + theBounds.getNorthEast().lng() + '&ne_x=' + theBounds.getNorthEast().lat(); $.get(url, function(newItemData) { handler.replace_markers(newItemData); }); } This outputs something like: /gigs.json.... sw_y=-148.84352170963916 sw_x=-13.80973371328428 ne_y=121.15647829036084 ne_x=87.24165143852134 Controller: def index @loc_search = true if (params[:sw_y] && params[:sw_x] && params[:ne_y] && params[:ne_x]) bounds = [ [params[:sw_x].to_f, params[:sw_y].to_f], [params[:ne_x].to_f, params[:ne_y].to_f] ] @gigs_within_bounds = Gig.within_bounding_box(bounds) else @gigs_within_bounds = Gig.all end if params[:search].present? @q = @gigs_within_bounds.where('date >= ?', Time.current.to_datetime).where(:filled => false).near(params[:search], 500, :order => 'distance' ).ransack(params[:q]) else @q = @gigs_within_bounds.where('date >= ?', Time.current.to_datetime).where(:filled => false).ransack(params[:q]) end @gigs = @q.result(distinct: true).page(params[:page]).per(20) @hash = Gmaps4rails.build_markers(@gigs) do |gig, marker| marker.infowindow render_to_string(:partial => "/gigs/infowindow", :locals => { :gig => gig}, :formats => [:html]) marker.lat gig.latitude marker.lng gig.longitude marker.title gig.title end respond_to do |format| format.html # index.html.erb format.js format.json { @data = @gigs.collect {|v| { :longitude => v.longitude, :latitude => v.latitude, } return render :json => @data }} end end My server is successfully filtering as I move the map; Eg. Processing by GigsController#index as JSON Parameters: {"sw_y"=>"50.14085329036084", "sw_x"=>"-83.09701329217522", "ne_y"=>"-39.85914670963916", "ne_x"=>"55.2456675702868"} Gig Load (0.3ms) etc etc etc... I am just getting confused on how to update the search results with this data. Any help would be greatly appreciated, thanks. |
It was really a nice post and i was really impressed by reading this Ruby on Rails Online Course
ReplyDelete