Rails how to update instance variable value at every execution Posted: 12 Mar 2016 07:12 AM PST I need to solve two problems with this piece of code inside a model. As far as I figured out the values in instance variables will be saved the first time it is executed, but since it is date and time it should be executed every time the method is called. How to go around that? Second, How can I access the instance variables inside the downtime method? def entry_time @day = DateTime.now.wday @date = Date.current @time = DateTime.now.hour if downtime errors.add(:_, "Please submit your request during working hours") end end def downtime holidays || @time < 9 || @time > 17 || @day == 6 || @day == 0 end Thanks a lot! |
Countdown timer with Javascript/JQuery in rails application Posted: 12 Mar 2016 06:56 AM PST What I would like to do is basically something like this: 1.Users sign up/ log in. OK 2.They create a new countdown and share it. NOPE 3.Other people just subscribe by email to the user. OK In the second point I am not really having a clear thought on how I can implement countdown timer creation and deletion. The creation part should be something like in this site: http://www.timeanddate.com/countdown/create If anyone can give any direction on how to do this implementation on a rails app please do. |
Ruby on Rails , Elasticsearch ,Tire , How to find a word in an attribute with LIKE QUERY and then Sort by relevance Posted: 12 Mar 2016 06:50 AM PST I want to search a word inside an attribute with Like Query ( I mean if i search 'Amirr' , 'Amirreza' returns as a result) and then I want to sort results with relevance to the search query parameter. Client.fullsearch({query: "username: #{params[:q]}*", page: 1 ,per_page: 25}) this code do the first part but I don't know how can I sort that with relevance. |
Creating a SCOPE for an association with more than 3 models - Rails 4 Posted: 12 Mar 2016 06:57 AM PST Could one kindly advise me where i am going wrong with my SQL query i want to display a company's list of forms that only have an accepted status @company.forms.created_this_month.forms_accepted.count but i get the below error. i am unsure where i am going wrong - any advise and help will be much appreciated error in terminal: 2.1.2 :043 > company.forms.created_this_month.forms_accepted Form Load (3.4ms) SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted') [["company_id", 1]] SQLite3::SQLException: ambiguous column name: status: SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted') ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: status: SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted') models company.rb has_many users has_many :forms, through: :users user.rb belongs_to company has_many adverts advert.rb belongs_to user has_many forms form.rb belongs_to advert scope :forms_accepted, -> {where(['status = ?', 'Accepted'])} scope :created_this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) } schema create_table "companies", force: true do |t| t.string "companyname" t.string "tel" t.string "email" end create_table "users", force: true do |t| t.string "email" t.string "firstname" t.string "lastname" t.integer "company_id" end create_table "adverts", force: true do |t| t.string "title" t.text "content" t.integer "user_id" end create_table "forms", force: true do |t| t.string "firstname" t.string "lastname" t.string "email" t.string "currentJob" t.string "currentEmployer" t.integer "advert_id" t.string "status" end |
Get tweet id using ruby on rails Posted: 12 Mar 2016 06:28 AM PST I am building an app to share a post on twitter using tweet button provided by twitter developers.On clicking the tweet button a new window open in which we can modify our tweet.There is one more tweet button on the new window.on clicking it our content gets tweeted. now I want to get id of the current tweet.It is shown in the url but i am unable to catch it in controller or in my database.Can any one help to sort this issue? |
Better practice to modularize code in mixins? Or just put all the code directly into the model? Posted: 12 Mar 2016 06:21 AM PST The title kind of says it all. I prefer to modularize code into mixins and include them into the model. My coworkers like to put the code directly into the model, potentially growing our model to MOUS's, models of unusual size. They think mixins are overkill. I'm wondering what you guys do/what's better practice out there in dev land. |
Ruby on Rails Dashboard partials Posted: 12 Mar 2016 05:52 AM PST I want to make a task-dasboard, but I have a few problems. What I want to achieve: I want to show multiple partials on one page, that respond to eachother. When you go to the dashboard you have two columns. The first column shows you the lists with all tasks and the second column shows you the details of one of the tasks you have clicked on in the first column (or automaticly the last made task in the list) Image to visualise what I want to achieve: https://gyazo.com/e87acf214e255817cdb03a22e3a35c4d At this moment my files look like this: application.html.erb <div class="main-content"> <section id="tasks"> <div class="wrapper"> <%= render partial: 'task_lists/index', collection: @task_lists %> </div> </section> <section id="description"> <%= render partial: 'task_lists/show', collection: @task_lists %> </section> <%= yield %> The <%= render partial: 'task_lists/index', collection: @task_lists %> already works so every task is listed in one column. The problem is that <%= render partial: 'task_lists/show', collection: @task_lists %> , doesn't work. This is the _show.html.erb where the 'broken' partial links to: <div class="row"> <div class="task_image"> <img src="../images/phone_img.png"></img> </div> <div class="task_heading"> <h1><%= @task_list.title %></h1> <p class="user_info">For <%= @task_list.client_email %></p> </div> <div class="task_content"> <%= render @task_list.task_items %> </div> <div class="task_finish"> <div class="row"> <p>Finish task</p> </div> </div> When I run the project, Rails says that the ID is undifined in the file _show.html.erb. My question: How can I make that Rails automaticly picks the first task unless someone clicked on a other task? So when you come on the dashboard you see the tasklist in the first column and Rails automaticly picks the first task and shows the details of it (_show.html.erb) in the second column. When you click on a other task in the first column you will get to see the details of that task in the second column. I hope my question is clear, ohterwise let me know. Thanks in advance. |
Using ruby on rails variables with Highchart Posted: 12 Mar 2016 06:29 AM PST I'm trying to create a column chart in my ruby on rails app. I have the basic graph set up, but for some reason I can't figure out how to dynamically change the data in my graph by using the variables i have created. <script type="text/javascript" charset="utf-8"> $(function () { new Highcharts.Chart({ chart: { renderTo: 'progress_chart', type: 'column'}, title: { text: 'My Weekly Progress' }, xAxis: { categories: ['Activity 1', 'Activity 2', ' Activity 3'], crosshair: true }, yAxis: { min: 0, max: <%=$extra%> , title: { text: 'Weeks' } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: 'Submitted', data: [<%= @submitted_array %>] }, { name: 'Approved', data: [83.6, 78.8, 98.5] }, { name: 'Weeks left', data: [48.9, 38.8, 39.3] }] }); }); </script> At the moment I am just trying to set the max of the yAxis to equal the variable $extra, but this doesn't seem to work. I am also trying to set the data for 'Submitted' to equal the following array which has been created within my controller: def show @submitted_array = $submitted1.to_s + ", " + $submitted2.to_s + ", " + $submitted3.to_s end Have I got incorrect syntax? Or am I calling my variables incorrectly? |
Use POST /sign_in to sign in. GET is not supported. Omniauth-facebook Posted: 12 Mar 2016 05:48 AM PST I've ng-token-auth for frontend and devise_token_auth on the backend . Now i've to implement omniauth-facebook & omniauth-goole logins in my website .Yet i've done facebook login with the following functions in config.js (ng-token-auth) $scope.handleBtnClick = function() { console.log('here its') $auth.authenticate('facebook') .then(function(resp) { // handle success }) .catch(function(resp) { // handle errors }); }; At this point , login occurs successfully , but when it redirects it shows me following error in my browser page {"errors":["Use POST /sign_in to sign in. GET is not supported."]} routes.rb mount_devise_token_auth_for 'User', at: 'auth',:controllers => { :omniauth_callbacks => 'omniauth' } devise.rb config.omniauth :facebook, 'APP_KEY', 'APP_SECRET',{ :scope => 'email' } omniauth controller class OmniauthController < Devise::OmniauthCallbacksController def facebook byebug @user = User.from_omniauth(request.env["omniauth.auth"]) sign_in_and_redirect @user end end ANd here are my server logs Started GET "/omniauth/facebook?auth_origin_url=http%3A%2F%2Flocalhost%3A3000%2F%23%2F&omniauth_window_type=sameWindow&resource_class=User" for 127.0.0.1 at 2016-03-12 18:34:33 +0500 I, [2016-03-12T18:34:33.203521 #5978] INFO -- omniauth: (facebook) Request phase initiated. Started GET "/omniauth/facebook/callback?code=AQARGivLmOz......" for 127.0.0.1 at 2016-03-12 18:34:34 +0500 I, [2016-03-12T18:34:34.189285 #5978] INFO -- omniauth: (facebook) Callback phase initiated. I, [2016-03-12T18:34:36.790185 #5978] INFO -- omniauth: (facebook) Callback phase initiated. E, [2016-03-12T18:34:36.790636 #5978] ERROR -- omniauth: (facebook) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected Processing by Devise::OmniauthCallbacksController#failure as HTML Parameters: {"code"=>"AQARGivLmOzsdLxe ..... "} Redirected to http://localhost:3000/auth/sign_in Completed 302 Found in 10ms (ActiveRecord: 0.0ms) Started GET "/auth/sign_in" for 127.0.0.1 at 2016-03-12 18:34:36 +0500 Processing by DeviseTokenAuth::SessionsController#new as HTML Completed 405 Method Not Allowed in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms) |
How to set image as a background from database in rails Posted: 12 Mar 2016 06:12 AM PST i'm a beginner in ruby on rails. so far I can only make a "create, show, delete, update data, and file upload using carrierwave" and I have problem when I want to set a image as background from database. i use carrierwave for image uploader and the image save in public/uploads/user/picture/ and this part of show.html.erb <p> <strong>Image:</strong><br> <%= image_tag @user.picture.thumb.url %> </p> then I have home.html.erb <div class="img-fill" style="background-image: url('..');"></div> - how to make an image into the background on the page home.html.erb of image I choose?
- What code should I add on show.html.erb to instruct the image used as background in home.html.erb? thx
|
Referring another model's method from current model's view Posted: 12 Mar 2016 05:55 AM PST I'm pretty new to Rails. I'm working on an app where you can upload a csv file or create a manual bank transaction. Previously I had both the manual entry and uploaded csv file entries in a single table called Transaction. Now I'm trying to store the uploaded file entries in a separate table called Bank. So I have a Bank model and a Transaction model and their respective controllers & views. Previously I had "New Transaction" form and "Upload CSV" form in the same page called "New Transaction" to avoid creating separate views for both and it was working fine. Now, After I've created a new model(Bank) for CSV uploaded entries, I tried to refer the Bank model's import method path from my "New Transaction" page to import csv files. But its returning me a Load Error. LoadError in BanksController#new Unable to autoload constant BanksController, expected /app/controllers/banks_controller.rb to define it This is my Bank Model: class Bank < ActiveRecord::Base belongs_to :admin paginates_per 10 def self.to_csv(options = {}) CSV.generate(options) do |csv| csv << column_names all.each do |transaction| csv << transaction.attributes.values_at(*column_names) end end end extend ActiveModel::Model include ActiveModel::Validations include ActiveModel::Conversion attr_accessor :file validates :date, presence: true validates :notes, presence: true validates :t_type, presence: true validates :t_method, presence: true validates :amount, presence: true validates :paid_by, presence: true validates :paid_to, presence: true #validates :cashbox, presence: true validates :bank, presence: true def self.import(file) CSV.foreach(file.path, headers: true) do |row| transaction_hash = row.to_hash t = Bank.new(transaction_hash.except("cashbox")) t.id = Bank.maximum(:id).next t.save! end end end This is my Bank Controller: class BankController < ApplicationController before_filter :authenticate_admin! def index @banks = Bank.all.order('created_at DESC') respond_to do |format| format.html format.csv { send_data @banks.to_csv } end end def import begin Bank.import(params[:file]) redirect_to root_url, notice: "Transactions Imported!" rescue ActiveRecord::RecordInvalid => exception redirect_to :back, alert: "#{exception.message}" end end def editview @q = Transaction.ransack(params[:q]) respond_to do |format| format.html format.csv { send_data @transactions_list_for_csv.to_csv, filename: 'transactions.csv' } end end end This is my New Transaction View from transaction model where it contains both forms for new transaction and upload csv: <div class="col-md-6"> <div class="container new-container"> <h3>New Transaction</h3> <%= render 'form' %> </br> <%= link_to "Back", root_path %> </div> </div> <div class="divider"></div> <div class="col-md-6"> <div class="import-col"> <h3>Import a CSV File:</h3> <%#= form_tag import_transactions_path, multipart: true do %> <%= form_tag import_banks_path, multipart: true do %> <%= file_field_tag :file, class: "form-control", required: true %></br> <%= submit_tag "Import CSV", class: "btn btn-success" %> <% end %> </div> </div> This is Transactions controllers new method: def new @transaction = Transaction.new end |
Nested Views with Dynamic Id's Angular & Rails Posted: 12 Mar 2016 05:39 AM PST Hey I have Angular rendering a list of Quotes as resources. The Quotes are stored in a rails back end. I am at the point where I would like to use Angular to render the show.html for that specific quote resource. I havent been able to get angular to resolve to the state. I'm not sure if I understand how to pass id's into state. I need help figuring out how to get angular to render the show.html in the ui-view labeled "fullquote" for the specific quote. Here is my code. Quotes.html <div class="quotes col-xs-10 col-md-8" ng-controller="QuotesCtrl" > <div ng-repeat="quote in quotes"> <a ng-click="showQuote(quote);"> <span ng-if="quote.read == false"> *NEW*</span> <span>Quote id: {{quote.id}}</span> <span>Name: {{quote.name}}</span> <span>Email: {{quote.email}}</span> <span>City: {{quote.city}}</span> <span>Region: {{quote.region}}</span> <span>State: {{quote.state}}</span> </a> <div ng-show="quote.visible"> <a ui-sref="quotes/{{quote.id}}"> View </a> <ui-view="fullquote"></ui-view="fullquote"> <a ng-click="quotes.splice($index, 1)"> Delete </a> <div ng-if""> <span> {{quote.question2 }}</span> <span> {{quote.question3 }}</span> <span> {{quote.question4 }}</span> <span> {{quote.question5 }}</span> <span> {{quote.question6 }}</span> <span> {{quote.question7 }}</span> <span> {{quote.question8 }}</span> <span> {{quote.question9 }}</span> <span> {{quote.question10 }}</span> <span> {{quote.question11 }}</span> <span> {{quote.question12 }}</span> <span> {{quote.question13}}</span> </div> </div> </div> </div> Quotes.js app.factory('Quotes', ['$resource',function($resource){ return $resource('/quotes.json', {},{ query: { method: 'GET', isArray: true }, create: { method: 'POST' } }) }]); app.factory('Quote', ['$resource', function($resource){ return $resource('/quotes/:id.json', {}, { show: { method: 'GET' }, update: { method: 'PUT', params: {id: '@id'} }, delete: { method: 'DELETE', params: {id: '@id'} } }); }]); app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '', templateUrl: 'static_pages/home.html'}) .state('quotes', { url: '/quotes', abstract: false, views : { templateUrl: 'quotes.html', controller: 'QuotesCtrl'}}) .state('quotes/:id', { url: 'quotes/:id', view: { "fullquote": { templateUrl: 'show.html', controller: 'QuotesCtrl'}}}) .state('quotes/:id.pdf', { url: 'quotes/:id.pdf', controller: 'QuotesCtrl'}) .state('users', { url: '/users', templateUrl: 'users.html', controller: 'UsersCtrl'}) .state('/users/:id', { url: 'users_show.html', controller: "UsersCtrl" }); $urlRouterProvider.otherwise( function($injector, $location) { var $state = $injector.get("$state"); $state.go("home"); }) $locationProvider.html5Mode({ enabled: true, requireBase: false }); }); app.controller("QuotesCtrl", ['$scope', '$state', '$http', 'Quotes', 'Quote', '$location', function($scope, $state, $http, Quotes, Quote, $location ) { $scope.quotes = Quotes.query(); $scope.quote = Quote.query(); $scope.showQuote = function (quote) { quote.visible = !quote.visible; } }]); |
Nokogiri and Openshift Posted: 12 Mar 2016 04:45 AM PST I have the following problem: I uploaded my rails app in openshift server and I obtained the followinf error: I searched in google but i didn't find solutions.. I have ruby 2.0 and rails 4. The strange thing is that in local my app works without problem but when I upload it, it doesn't work cause of this "nokogiri". Can you help me? I'm on Windows 8 and in local it works. HERE my Gemfile and Gemlock source 'https://rubygems.org' gem 'rails', '4.2.4' gem 'sqlite3' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc group :development, :test do gem 'byebug' end group :development do gem 'web-console', '~> 2.0' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :jruby] gem 'rake' gem 'rack' gem 'nokogiri' GEMLOCK GEM remote: https://rubygems.org/ specs: actionmailer (4.2.4) actionpack (= 4.2.4) actionview (= 4.2.4) activejob (= 4.2.4) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (4.2.4) actionview (= 4.2.4) activesupport (= 4.2.4) rack (~> 1.6) rack-test (~> 0.6.2) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (4.2.4) activesupport (= 4.2.4) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) activejob (4.2.4) activesupport (= 4.2.4) globalid (>= 0.3.0) activemodel (4.2.4) activesupport (= 4.2.4) builder (~> 3.1) activerecord (4.2.4) activemodel (= 4.2.4) activesupport (= 4.2.4) arel (~> 6.0) activesupport (4.2.4) i18n (~> 0.7) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) arel (6.0.3) binding_of_caller (0.7.2) debug_inspector (>= 0.0.1) builder (3.2.2) byebug (8.2.2) coffee-rails (4.1.1) coffee-script (>= 2.2.0) railties (>= 4.0.0, < 5.1.x) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.10.0) concurrent-ruby (1.0.1) debug_inspector (0.0.2) erubis (2.7.0) execjs (2.6.0) globalid (0.3.6) activesupport (>= 4.1.0) i18n (0.7.0) jbuilder (2.4.1) activesupport (>= 3.0.0, < 5.1) multi_json (~> 1.2) jquery-rails (4.1.1) rails-dom-testing (>= 1, < 3) railties (>= 4.2.0) thor (>= 0.14, < 2.0) json (1.8.3) loofah (2.0.3) mail (2.6.3) mime-types (>= 1.16, < 3) mime-types (2.99.1) mini_portile2 (2.0.0) minitest (5.8.4) multi_json (1.11.2) mini_portile2 (~> 2.0.0.rc2) nokogiri (1.6.7.2-x86-mingw32) mini_portile2 (~> 2.0.0.rc2) rack (1.6.4) rack-test (0.6.3) rack (>= 1.0) rails (4.2.4) actionmailer (= 4.2.4) actionpack (= 4.2.4) actionview (= 4.2.4) activejob (= 4.2.4) activemodel (= 4.2.4) activerecord (= 4.2.4) activesupport (= 4.2.4) bundler (>= 1.3.0, < 2.0) railties (= 4.2.4) sprockets-rails rails-deprecated_sanitizer (1.0.3) activesupport (>= 4.2.0.alpha) rails-dom-testing (1.0.7) activesupport (>= 4.2.0.beta, < 5.0) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.3) loofah (~> 2.0) railties (4.2.4) actionpack (= 4.2.4) activesupport (= 4.2.4) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (11.1.0) rdoc (4.2.2) json (~> 1.4) sass (3.4.21) sass-rails (5.0.4) railties (>= 4.0.0, < 5.0) sass (~> 3.1) sprockets (>= 2.8, < 4.0) sprockets-rails (>= 2.0, < 4.0) tilt (>= 1.1, < 3) sdoc (0.4.1) json (~> 1.7, >= 1.7.7) rdoc (~> 4.0) sprockets (3.5.2) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.0.4) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sqlite3 (1.3.11-x86-mingw32) thor (0.19.1) thread_safe (0.3.5) tilt (2.0.2) turbolinks (2.5.3) coffee-rails tzinfo (1.2.2) thread_safe (~> 0.1) tzinfo-data (1.2016.1) tzinfo (>= 1.0.0) uglifier (2.7.2) execjs (>= 0.3.0) json (>= 1.8.0) web-console (2.3.0) activemodel (>= 4.0) binding_of_caller (>= 0.7.2) railties (>= 4.0) sprockets-rails (>= 2.0, < 4.0) PLATFORMS x86-mingw32 DEPENDENCIES byebug coffee-rails (~> 4.1.0) jbuilder (~> 2.0) jquery-rails nokogiri rack rails (= 4.2.4) rake sass-rails (~> 5.0) sdoc (~> 0.4.0) sqlite3 turbolinks tzinfo-data uglifier (>= 1.3.0) web-console (~> 2.0) BUNDLED WITH 1.10.4 |
Rendering shared partial in SonarQube Plugin Posted: 12 Mar 2016 04:32 AM PST I have two plugins for SonarQube and I would like them to share RoR partials. So in Plugin A I have a view with: <%= render :partial => 'B/app/views/sharedpartial' %> In Plugin B I have a view B/app/views/_sharedpartial.html.erb Both are being deployed by SonarQube correctly to the folder temp/ror/<PluginKey> , but Plugin A isn't rendering the sharedpartial . Do SonarQube Plugins not have read access to each others files? Or am I making a mistake in RoR? The platform is SonarQube 4.5.x LTS Thanks. |
AJAX 404 Error in Rails View Posted: 12 Mar 2016 04:16 AM PST I'm trying to load the comment for each article on my index page using AJAX. What am I missing here? Index: #welcome/index.haml - @articles.each do |article| = article.title - article.comments.each do |comment| %comment-content{ :id => "comment-<%= comment.id %>", :class => "comment-block", "data-comment-id" => "<%= comment.id %>"} Controller: #comments_controller.rb class CommentsController < ApplicationController def show respond_to do |format| format.js { } end end end JS: #comments.js var loadComment; loadComment = function() { return $('.comment-block').each(function() { var $comment_block; $comment_block = $(this); return $.ajax('/comments/show', { type: 'GET', dataType: 'script', data: { comment_id: $comment_block.data('comment-id') }, error: function(jqXHR, textStatus, errorThrown) { return console.log("AJAX Error: " + textStatus); }, success: function(data, textStatus, jqXHR) { return console.log("Worked OK!"); } }); }); }; $(document).ready(loadComment); $(document).on('page:change', loadComment); Show: #comments/show.js.erb $('#comment-<%= @comment.id %>').append('j render(@comment.content)'); EDIT: So the console log displays the following link but I guess the correct URL would be localhost:3000/articles/1/comment/1 How do I fix it? Console log: http://localhost:3000/show?comment_id=%3C%25%3D+comment.id+%25%3E&_=1457784667124 routes.rb resources :articles do resources :comments do end end |
Rails custom fonts Posted: 12 Mar 2016 04:01 AM PST After following this guide I'm still not able to use my custom font in my Rails application. This is my new Assets file structure: |-app/ |---assets/ |-----fonts/ |-----images/ |-----javascripts/ |-----stylesheets/ In the fonts directory I placed a file named: "Hurme Design - HurmeGeometricSans3 Regular" I edited my config/application.rb which now looks like so: require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Criteofootball class Application < Rails::Application config.assets.paths << Rails.root.join("app", "assets", "fonts") # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end In my scss file I wrote the following in order to apply the font to all my HTML elements: @font-face { font-family: "Hurme Design"; src: font-url(Hurme Design - HurmeGeometricSans3 Regular); } html * { font-family: "Hurme Design" !important; } Thanks a lot in advance! |
SQLite3 error in rails SQLite3::SQLException: no such column Posted: 12 Mar 2016 06:07 AM PST I am making a rails app where a user can post courses and also subscribe to courses.My model files are: user.rb: class User < ActiveRecord::Base has_many :courses, dependent: :destroy has_many :coursejoins, dependent: :destroy has_many :learnables, through: :coursejoins, class_name: "Course" has_many :comments, dependent: :destroy ... end course.rb: class Course < ActiveRecord::Base belongs_to :user belongs_to :category has_many :coursejoins, dependent: :destroy has_many :students, through: :coursejoins, class_name: "User" has_many :documents, dependent: :destroy has_many :comments, dependent: :destroy ... end coursejoin.rb: class Coursejoin < ActiveRecord::Base belongs_to :learnable, :class_name => "Course" belongs_to :student, :class_name => "User" end 20160219171527_create_coursejoins.rb class CreateCoursejoins < ActiveRecord::Migration def change create_table :coursejoins do |t| t.boolean :accepted t.timestamps end end end 20160219174937_add_student_id_to_coursejoins.rb class AddStudentIdToCoursejoins < ActiveRecord::Migration def change add_column :coursejoins, :student_id, :integer end end 20160219224309_add_learnable_id_to_coursejoins.rb class AddLearnableIdToCoursejoins < ActiveRecord::Migration def change add_column :coursejoins, :learnable_id, :integer end end The coursejoin model is like a relation between a course and a user. When I try to do @course.students, i get error: SELECT "users".* FROM "users" INNER JOIN "coursejoins" ON "users"."id" = "coursejoins"."student_id" WHERE "coursejoins"."course_id" = ? [[nil, 1]] ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: coursejoins.course_id: SELECT "users".* FROM "users" INNER JOIN "coursejoins" ON "users"."id" = "coursejoins"."student_id" WHERE "coursejoins"."course_id" = ? I don't know SQL much so I am not able to decipher the error. I looked at questions with similar error but none seemed related. I have been stuck with this for two days. How do I fix this? |
Rails referral marketing on discount Posted: 12 Mar 2016 03:45 AM PST I am trying to build a referral marketing system on rails. Searched on various web pages for information could not find any helpful content. What I would like to do is, I have created a user model, who can sign in - out OK. Then they can type a email address to text_field to send a email to friends saying "come join us" etc. The referred user clicks to link come backs to site when he signs up to site, I will give a discount for instance. For the sake of clarity lets say the main user's email address is jack@gmail.com, who wants to send to his friend alex@gmail.com. Alex receives and email "come join us". He clicks and signs up, and gets discount. How can I know that Alex clicked on the link and signed up. I should be generating some come attached to the link in the email address but not sure how to do it. Thank you for your help! |
rails - HasManyThroughAssociationNotFoundError on plural has_many Posted: 12 Mar 2016 06:04 AM PST I have the following models: User Team UserTeam There are users and there are teams. Each team has 0 or more users, the join table is UserTeams I want to get all teams and for each team get its users. Initially I tried for one team and get its users, like this Team.find('759ccbb7-2965-4558-b254-3e437ca721aa').users but rails complains about this with: Could not find the association :user_team in model Team This is how my Team model looks like: class Team < ActiveRecord::Base has_many :users, through: :user_team has_many :user_teams, dependent: :destroy accepts_nested_attributes_for :user_teams, :reject_if => lambda { |a| a[:user_id] == '0' } validates :name, presence: true end Team model: class UserTeam < ActiveRecord::Base belongs_to :team belongs_to :user validates :user_id, presence: true end Weird enough, if I change Team model like this: has_many :user_team using the singular word, it works, but I read that it has to be pluralized |
Acts as votable JSON put Posted: 12 Mar 2016 03:00 AM PST I have a working rails app, which is a blog with comments and upvoting/downvoting. The mobile component is for users to log in/log out, view articles and upvote/downvote, not add articles or comments at this stage. I have implemented the json login with the simple token auth gem and I can get the articles and their upvotes/downvotes which is all working but here is my problem: How do I post the json values back? I have my json code working in Android to post or push json values but how do I build the correct string to push back? What is the correct parameters to put back? Thanks very much. This is from rails server log: The html upvote which works: Started PUT "/articles/5/like" for 137.147.172.125 at 2016-03-12 09:34:43 +0000 Cannot render console from 137.147.172.125! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by ArticlesController#upvote as HTML Parameters: {"authenticity_token"=>"4eC8xgC+1CBb51gKO7ZRzjL1BGOF6TYTnbqQcJ3evxvpmGcguYHBNYSn9v3LJMfoo3F29frntwzgyLoeI9oaLg==", "id"=>"5"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]] Article Load (0.1ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? ORDER BY "articles"."created_at" DESC LIMIT 1 [["id", 5]] (0.3ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL [["votable_id", 5], ["votable_type", "Article"], ["voter_id", 1], ["voter_type", "User"]] (0.2ms) begin transaction SQL (0.6ms) INSERT INTO "votes" ("votable_id", "votable_type", "voter_id", "voter_type", "vote_flag", "vote_weight", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["votable_id", 5], ["votable_type", "Article"], ["voter_id", 1], ["voter_type", "User"], ["vote_flag", "t"], ["vote_weight", 1], ["created_at", "2016-03-12 09:34:43.393685"], ["updated_at", "2016-03-12 09:34:43.393685"]] (11.4ms) commit transaction Redirected to https://completerubyonrailscourse-adam1st.c9users.io/articles/5 Completed 302 Found in 187ms (ActiveRecord: 13.2ms) This is when my android code attempts to push the json data back to the rails server: Started PUT "/articles/5/like" for 49.199.131.149 at 2016-03-12 10:20:16 +0000 Cannot render console from 49.199.131.149! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by ArticlesController#upvote as JSON Parameters: {"votes"=>{"votable_id"=>"5", "votable_type"=>"Article", "voter_id"=>"1", "voter_type"=>"User", "vote_flag"=>"t", "vote_weight"=>"1", "created_at"=>"2016-03-12 21:20:13.679000", "updated_at"=>"2016-03-12 21:20:13.679000"}, "id"=>"5", "article"=>{}} Can't verify CSRF token authenticity Completed 401 Unauthorized in 2ms (ActiveRecord: 0.0ms) So how do I get this into the json data? Parameters:{"authenticity_token"=>"4eC8xgC+1CBb51gKO7ZRzjL1BGOF6TYTnbqQcJ3evxvpmGcguYHBNYSn9v3LJMfoo3F29frntwzgyLoeI9oaLg==", "id"=>"5"} From the articles controller: before_action :authenticate_user!, :except => [:index, :show] before_filter :set_article, only: [:show, :edit, :update, :destroy, :upvote, :downvote] . . . def upvote @article.upvote_by current_user flash[:success] = "Successfully liked" respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @article.liked_count } } end end def downvote @article.downvote_by current_user flash[:success] = "Successfully disliked" respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @article.disliked_count } } end end From the show.html.erb that concerns the voting: <%= link_to like_article_path(@article), method: :put, class: 'voting' do %> <i class="fa fa-thumbs-up"></i> <%= @article.get_upvotes.size %> <% end %> <%= link_to dislike_article_path(@article), method: :put, class: 'voting' do %> <i class="fa fa-thumbs-down"></i> <%= @article.get_downvotes.size %> <% end %> Android PUT code (some values hard coded for testing): private class VoteTask extends UrlJsonAsyncTask { public VoteTask(Context context) { super(context); } @Override protected JSONObject doInBackground(String... urls) { HttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(urls[0]); JSONObject holder = new JSONObject(); JSONObject voteObj = new JSONObject(); String response = null; JSONObject json = new JSONObject(); try { try { // setup the returned values in case // something goes wrong json.put("success", false); json.put("info", "Something went wrong. Retry!"); // add the user email and password to // the params voteObj.put("votable_id",articleId); voteObj.put("votable_type", "Article"); voteObj.put("voter_id", "1"); voteObj.put("voter_type", "User"); voteObj.put("vote_flag", "t"); voteObj.put("vote_weight", "1"); voteObj.put("created_at", strDate); voteObj.put("updated_at", strDate); holder.put("votes", voteObj); StringEntity se = new StringEntity(holder.toString()); put.setEntity(se); // setup the request headers put.setHeader("Accept", "application/json"); put.setHeader("Content-Type", "application/json"); response = String.valueOf(client.execute(put)); json = new JSONObject(response); } catch (IOException e) { e.printStackTrace(); Log.e("IO", "" + e); } } catch (JSONException e) { e.printStackTrace(); Log.e("JSON", "" + e); } return json; } |
Rails: Can't add CSS class from variable in link_to Posted: 12 Mar 2016 03:13 AM PST SyntaxError occurs when: <% @list1.each do |list| %> <div class="well well-sm"> <%= list.test_name %> <%= link_to 'Do It', '#', class: <%= list.test_type %> </div> <% end %> Tried also class: <%= #{list}.test_type %> and so on... what's wrong with it? |
Using Turbolinks without asset pipeline? Posted: 12 Mar 2016 02:07 AM PST I am building a Rails 5 webapp around a premade HTML5 template. I would like to use Turbolinks as it would heavily complement the purposes of the application. However, I chose not to use the Rails asset pipeline because everything in the HTML/CSS files of the template is statically linked with absolute paths. The turbolinks documentation specifies an entry to be made in the Javascript manifest. However, will it still work if nothing else is being processed by the asset pipeline? |
How to stub searchkick in search method in controller Posted: 12 Mar 2016 01:31 AM PST I am new to rspec and I want to test my search controller, I try to stub my search method in controller but it always fails. Failure/Error: expect(Doctor).to receive(:search).with(search_param) (<Doctor(id: integer, name: string, address: string, phone: string, is_active: boolean, field_id: integer, created_at: datetime, updated_at: datetime, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: inet, last_sign_in_ip: inet, roles: integer, description: text, avatar_file_name: string, avatar_content_type: string, avatar_file_size: integer, avatar_updated_at: datetime, avatar_processing: boolean, title: string, valid_doctor: boolean, verification_photo_file_name: string, verification_photo_content_type: string, verification_photo_file_size: integer, verification_photo_updated_at: datetime) (class)>).search("rizky") expected: 1 time with arguments: ("rizky") received: 0 times What's the correct way to isolate searchkick? Here is my search method in controller: def search @doctors = [] keyword = params[:keyword] @doctors = call_search_in_doctor(keyword) if keyword.present? respond_to do |format| format.json { render json: @doctors, status: 200 } format.html { render 'users/search/index.html.haml', status: 200 } end end def call_search_in_doctor(keyword) Doctor.search keyword, misspellings: { edit_distance: 3 }, page: params[:page], per_page: 10, limit: 100, fields: [{ name: :word }, { name: :word_start }, { name: :word_middle }, { name: :word_end }, :code, :field_name] end And here is my controller test: context 'with keyword' do let(:search_param) { "rizky" } let(:doctor) { instance_double(Doctor) } let(:results) { instance_double(Searchkick::Results) } before do allow(Doctor).to receive(:search).with(search_param) {:results} end it 'calls Doctor.search' do get :search, search_param expect(Doctor).to receive(:search).with(search_param) end end Thanks for your precious time! |
rails array mixing text and integer Posted: 12 Mar 2016 02:22 AM PST With def change create_table :something do |t| t.text :keyword, array: true, default: [] end end I want to make a data that is like [["a", 1],["b", 5]]. it worked unexpectedly. like, e.keyword = [["a", 1],["b",2]] => [["a", 1], ["b", 2]]. Is this the right way to implement it in rails4? |
Rails4: NoMethodError in UsersController#show, undefined method Posted: 12 Mar 2016 06:30 AM PST I'd like to develop an app for schedule. Each user create their own schedule. I'd like to display the data as followings; schedule title (user name) day1(mm/dd,yyyy) 09:00 Math 11:00 Science Room name A day2(mm/dd,yyyy) 10:00 Physics 13:00 Music Room name B How can I display course information in the event model? e.g. title (Math, Science), time (from, to)... The following error appeared when I try to display the page. NoMethodError (undefined method `event' for #<Room:0x007fb2149a1ac8> Did you mean? events events=): app/views/schedules/_schedule.html.erb:6:in `block in _app_views_schedules__schedule_html_erb___2809280481749604534_70201410929300' app/views/schedules/_schedule.html.erb:4:in `_app_views_schedules__schedule_html_erb___2809280481749604534_70201410929300' app/views/users/show.html.erb:11:in `_app_views_users_show_html_erb__1629176981125983348_70201561746560' It would be appreciated if you could give me any suggestion. user.rb class User < ActiveRecord::Base has_many :schedlues has_many :rooms, through: :schedules ... schedule.rb class Schedule < ActiveRecord::Base belongs_to :user has_many :rooms ... room.rb class Room < ActiveRecord::Base belongs_to :schedlue has_many :events event.rb class Event < ActiveRecord::Base belongs_to :room (Although I think 'room has_many events' is improper, I don't have any idea.) schema create_table "users", force: :cascade do |t| t.string "name" t.string "email" ... end create_table "schedules", force: :cascade do |t| t.string "title" t.integer "user_id" ... end create_table "rooms", force: :cascade do |t| t.date "date" t.string "room_name" t.integer "schedule_id" ... end create_table "events", force: :cascade do |t| t.time "from" t.time "to" t.string "title" ... end users_controller.rb class UsersController < ApplicationController def show @user = User.find(params[:id]) @schedules = @user.schedules.paginate(page: params[:page]) end ... show.html.erb <% if @user.schedules.any? %> <ol class="schedules"> <%= render @schedules %> </ol> <%= will_paginate @schedules %> <% end %> _schedule.html.erb <li> <p> <% schedule.room.each do |a| %> <p><b>Day <%= a.day %></b></p> <% a.event.each do |e| %> #error occur <% if e.title.any? %> <%= e.title %> <% end %> <% end %> <p>room: <%= a.room_name %></p> <% end %> </p> </li> |
How to replicate this specific curl query in Ruby/Ror? Posted: 12 Mar 2016 12:44 AM PST The following curl works perfectly fine. curl -g "[external-url]" --data-urlencode 'JsonData={"TOKEN":"[token]","MID":"[merchant_id]"}' But I am trying to replicate the same in Ruby/Ror. The closest I have to is the following, but to no avail. params = {JsonData: '{"TOKEN":"[token]","MID":"[merchant_id]"}'} url = [external-url] uri = URI(url) request = Net::HTTP::Get.new(uri.path, initheader = {'Content-Type' =>'application/json'}) request.add_field('session_token', access_token) request.body = params.to_json response = Net::HTTP.start( uri.hostname, uri.port, :use_ssl => uri.scheme == 'https' , :verify_mode => OpenSSL::SSL::VERIFY_PEER ) do |http| http.request(request) end |
data attribute returns duplicated array #rails Posted: 12 Mar 2016 12:49 AM PST So I have a link that has data passed into it. I access that data from the click function in jquery. But when I alert the data objects, it alerts the first object twice. I don't know why it does that. I printed the size of the data and it said 2. But I made sure that the product's names are all unique. Here is my code: == link_to "button", "#", class: "h3", id: "#{product.name}", data: {products: @products.limit(2)} js: $('.h3').click(function(e) { var id = this.id; var data = $(id).data('products'); alert(data[0].name, data[1].name); } |
Cloud Foundry - Rails 4 database.yml Posted: 12 Mar 2016 04:32 AM PST I am trying to deploy my Rails 4 app which uses a mysql database. The database is hosted on a different server. I am confused as how my database.yml file should be configured, and how does cloud foundry know which section to use. After deployment, I get this error when loading my app ActiveRecord::AdapterNotSpecified '' database is not configured. Available: ["development"] Rails.root: /home/vcap/app If you then refresh the page, you get: NoMethodError undefined method `default_timezone=' for #<Class:0x007fd7930ab0f0> Rails.root: /home/vcap/app My database.yml is like this: #local development development: adapter: mysql2 encoding: utf8 host: hostname port: 3306 database: appdb username: myapp password: 'password' timeout: 5000 # 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: &test adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 production: adapter: mysql2 encoding: utf8 host: hostname port: 3306 database: appdb username: myapp password: 'password' timeout: 5000 |
ajax call not updating content on rails Posted: 12 Mar 2016 01:25 AM PST Im trying to implement a bit a Ajax into my app seems to work correctly but it isnt updating the page after the action is executed . I added Ajax to my Destroy method def destroy @item = Item.find(params[:id]) @item.user = current_user if @item.destroy flash[:notice] = "Item Completed" else flash[:alert] = "Item was unable to be marked completed " end respond_to do |format| format.html format.js end end i have update my _item.html.erb and _form.html.erb partials with remote: true <%= content_tag :div, class: 'media', id: "item-#{item.id}" do %> <div class="media"> <div class="media-body"> <small> <%= item.name.titleize %> | submitted <%= time_ago_in_words(item.created_at) %> <% if current_user == @user %> <%= link_to "Completed ", [@user, item], method: :delete,remote: true, class: 'glyphicon glyphicon-ok' %><br> <% end %> </small> </div> </div> <% end %> _from.html.erb <%= form_for [@user, item ], remote: true do |f|%> <div class="form-group"> <%= f.label :name, class: 'sr-only' %> <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %> </div> <%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %> <% end %> User#show view <div class='new_item'> <%= render :partial => 'items/form', :locals =>{:item => Item.new} %> </div> <% end %> <div class='js-items'> <% @user.items.order('created_at DESC').each do |item| %> <%= render :partial => 'items/item' , :locals => {:item => item } %> </div> destroy.js.erb $('#item-<%= @item.id %>').hide(); Like I said before, the item is deleted when i click the delete button but i need to refresh the page in order to see the updated page. Any ideas what i might be doing wrong, any push to the right direction would be greatly appreciated! |
Rails and Google Plus API Posted: 11 Mar 2016 11:13 PM PST I'm making a rails API where I receive access tokens for Facebook and Google+ from the mobile, and I need to get information from them through the tokens. For Facebook, I did it very easily through graph API with a simple URL like this: https://graph.facebook.com/v2.5/me?fields=id&&access_token=#{access_token} but I can't seem to find anything similar for Google+. Any help? |
No comments:
Post a Comment