Saturday, April 30, 2016

How many app may be deploy on my VPS | Fixed issues

How many app may be deploy on my VPS | Fixed issues


How many app may be deploy on my VPS

Posted: 30 Apr 2016 07:03 AM PDT

I have a VPS that have : RAM : 512 MB, CPU : single core, OS : centos , and unicorn server .

And have 50 GB disk space I want to know how many rails app i can deploy on this vps . Or totally what a rule between number of apps and vps's informations ?

Routing Error: No route matches [POST] "/flex_quiz/new"

Posted: 30 Apr 2016 06:37 AM PDT

In my rails app I'm trying to use a form partial to display the same quiz on the new and edit views. I can see the new view page, but when I hit <%= f.submit "Submit Answers" %> I get an error saying No route matches [POST] "/flex_quiz/new".

Here is the form for line in my partial:

<%= form_for @flex_quiz, url: url do |f| %>  

And here's how the locals stand in my new view:

 <%= render partial: "quiz", locals: { url: new_flex_quiz_path, method: :post } %>  

And my edit view:

<%= render "quiz", url: edit_flex_quiz_path(@flex_quiz), method: :put  %>  

Here are the route paths:

         Prefix Verb   URI Pattern                    Controller#Action              ...       flex_quiz_index GET    /flex_quiz(.:format)           flex_quiz#index                  POST   /flex_quiz(.:format)           flex_quiz#create    new_flex_quiz GET    /flex_quiz/new(.:format)       flex_quiz#new   edit_flex_quiz GET    /flex_quiz/:id/edit(.:format)  flex_quiz#edit        flex_quiz GET    /flex_quiz/:id(.:format)       flex_quiz#show                  PATCH  /flex_quiz/:id(.:format)       flex_quiz#update                  PUT    /flex_quiz/:id(.:format)       flex_quiz#update                  DELETE /flex_quiz/:id(.:format)       flex_quiz#destroy  

Can anyone suggest how to fix this? I have looked at several similar posts (like this and this) but since I'm using partials the solution here is going to have to be a bit different.

Ruby on rails bootstrap css js working but not found

Posted: 30 Apr 2016 06:37 AM PDT

I have a rails application which I added the bootstrap gem

first I added this two gems

gem 'bootstrap'  gem 'sprockets-rails', :require => 'sprockets/railtie'  

which installed this packages

Using bootstrap 4.0.0.alpha3  Using sprockets 3.6.0  

After I modified application.scss to

// Custom bootstrap variables must be set or import before bootstrap itself.  @import "bootstrap";  

Then I left application.js like this

// 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 any plugin's vendor/assets/javascripts directory 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  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require turbolinks  //= require tether  //= require bootstrap-sprockets  //= require_tree .  //= require_self  

Lastly my application.html.erb is this

<!DOCTYPE html>  <html>  <head>    <title>Squirm</title>    <%= stylesheet_link_tag    "bootstrap"  %>   <%= javascript_include_tag "bootstrap" %>   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>   <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>   <%= csrf_meta_tags %>  </head>  <body>    <%= render 'partials/navbar' %>      <div class="container">      <%= yield %>    </div>    </body>  </html>  

Bootstrap seems to we working, but in the Google Chrome console seems not to be found

enter image description here

Rails5/Devise 4.0.1 Overriding Confirmations controller to allow password at activation: Token Blank

Posted: 30 Apr 2016 06:35 AM PDT

Using the wiki tutorial, I've implemented the gradual engagement approach to registration.

Now, after clicking the "confirm" link in email, the password page will say "Confirmation token can't be blank".

It's being submitted in the form, I can see the params passed in the log, but it's a hash params[:user][:confirmation_token], not params[:confirmation_token].

How can I remedy this issue?

Rails Tutorial- cannot get rails to recognize route

Posted: 30 Apr 2016 06:29 AM PDT

I am new to programming in general, someone referred me to railstutorial.org.

Specs: I am working on a cloud9 IDE, as suggested in the tutorial.

Information: I am on 1.3 of the rails tutorial, which is setting the root route. The problem was initially my route did not effect the server launch (root page was still ruby default, not to 'application#hello'). Here are the files that the tutorial said to edit.

routes.rb

Rails.application.routes.draw do  root to: 'application#hello'  end  

application_controller.rb

class ApplicationController < ActionController::Base  protect_from_forgery with: :exception  def hello  render text: "Hello, world!"  end  end  

There are a lot of comments that were defaulted into the files that I left out.

I have followed the instructions precisely. After I first had trouble, I thought I may have made an installation error, so I deleted my IDE and restarted, paying extreme attention to detail, especially versions.

I have tried $ rake routes, and my understanding it gives the message:

You don't have any routes defined!  

That leads me to believe that the problem is the routes.rb file. I have tried changing the syntax to:

root to: 'application#hello'  

I don't know a whole lot, such as how it would work using application, so I also tried:

root 'ApplicationController#hello'  

and

root to: 'ApplicationController#hello'  

These all result in the no routes defined message. I have no idea what is going on.

Thanks for any input or help!

Rails 4.2.6 FactoryGirl with polymorphic association

Posted: 30 Apr 2016 06:13 AM PDT

I have a problem setting up factories for my polymorphic associations with FactoryGirl. My model and factory setup looks like this:

class Address < ActiveRecord::Base    belongs_to :addressable, polymorphic: true  end    class Customer < ActiveRecord::Base    has_one :address, as: :addressable  end     factory :address do        village Faker::Address.city        upazilla Faker::Address.street_name        ward Faker::Address.street_address        district Faker::Address.state        association :addressable  end      factory :customer ,class: Customer do         recharge_token 10         date_of_birth Faker::Date.backward(100)        manager        after(:create) do |customer|            customer.address = create(:address, addressable: customer)          #create( :address, addressable: customer)        end       end  

The test suite breaks with the following error message

 vendor/cache/ruby/2.2.0/gems/factory_girl-4.7.0/lib/factory_girl/linter.rb:12:in `lint!': The following factories are invalid: (FactoryGirl::InvalidFactoryError)   * address - Factory not registered: addressable (ArgumentError)  

This is exactly my problem but unfortunately his solution is not working for me. Thanks you all for your time!

Show brings up a list of data

Posted: 30 Apr 2016 06:07 AM PDT

I am trying to show a list of all the items I've created. (Called "join") In the show.html.erb, I wrote

<%= @join = Join.all %>    <%= @join.each do |join| %>    <%= join.email %>  <% end %>  

And It's working, but when I go to the page I get a bunch of data that says: #<Join::ActiveRecord_Relation:0x007fbca99f12b8> sbhenrichs@gmail.com [#<Join id: 1, email: "sbhenrichs@gmail.com", created_at: "2016-04-30 12:48:16", updated_at: "2016-04-30 12:48:16">] Does anybody know how to get rid of that?

Rails 4 Image gallery options? [on hold]

Posted: 30 Apr 2016 06:41 AM PDT

I am wondering how to display multiple images when a user clicks on a thumbnail using Rails 4.

For example, a user clicking on a thumbnail in an image gallery full of shoes will display the image of the shoe in a dimmed pop-up window, but also allow the user to navigate left and right from that one thumbnail, to see multiple images of the shoe taken at different angles; the multiple angles of the shoes should be hidden unless clicked on by the user.

I have heard of the paperclip gem, but the tutorials I have seen seem to focus more on single images displayed in a gallery.

stderr /usr/local/bin/bundle: argument list too long while bundle install

Posted: 30 Apr 2016 05:06 AM PDT

I am using ansible to do deployment for my rails app. The problem is when a new gem is added and the ansible runs bundle install, it gives the following error:

stderr /usr/local/bin/bundle: argument list too long  /usr/local/bin/bundle: line 7: /usr/local/bin/bundle: success  

The ansible task to do bundle install is

- name: Bundle install    command: 'bundle install --deployment --without development test'    register: bundler    args:      chdir: '/home/ubuntu/myproject'  

I am using rvm to manage ruby version. Using ruby-2.2.1 and I have set rvm to use gemset of myproject i.e. rvm use ruby-2.2.1@myproject.

The .rvm/gems/ directory have ruby-2.2.1/ ruby-2.2.1@global/ ruby-2.2.1@myproject/

I have specified passenger_ruby /home/ubuntu/.rvm/wrappers/ruby-2.2.1@myproject/ruby

This happens only when new gem is added in Gemfile, when there is only code update, everything works fine. If I run bundle install explicitly doing ssh to corresponding instance, it works fine and install the gem. Any help and suggestion on this?

Rails, CarrierWave and AngularJS ngFileUpload

Posted: 30 Apr 2016 04:41 AM PDT

I have been trying to upload images for the past couple of hours using ngFileupload and had no luck, I am building a SPA (for learning purposes) using rails and angularJS for upload I am using Carrierwave.

Here goes the problem, I have no clue what I am doing at this stage I have added Ng-file-uploader to my app as follows:

var app = angular.module('myApp', ['ui.router', 'ngResource', 'templates', 'Devise', 'ngAnimate', 'ngFileUpload']);  

and in the projectCtrl it is as follows:

app.controller('NewProjectCtrl', ['$scope', 'ProjectsSvc', '$state','Upload', function($scope, ProjectsSvc, $state, Upload){    $scope.upload = function (file) {           Upload.upload({               url: '/projects',               data: {file: file, 'filename': $scope.project.title}           }).then(function (resp) {               console.log('Success ' + resp.config.file.name + 'uploaded. Response: ' + resp.data);           }, function (resp) {               console.log('Error status: ' + resp.status);           }, function (evt) {               var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);               console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);           });       };    $scope.project = new ProjectsSvc();    $scope.addProject = function() {      $scope.upload($scope.file);      $scope.project.$save(function(){});    };  

Now everytime I try to create a new project I get the following error

enter image description here

Any help would be greatly appreciated.

P.S. two weeks ago I was clueless when it came to JavaScript and AngularJS

RoR app - 'gem install mysql' error when running 'cap production deploy:initial'

Posted: 30 Apr 2016 04:18 AM PDT

I'm attempting to deploy my Ruby on Rails app to a DigitalOcean droplet and I've been using this guide on how to do so, I followed a guide previously on how to deploy (a youtube video tutorial) but it didn't work so I've attempted this written guide. Everything has been working so far except when I attempt to deploy using cap production deploy:initial I get the following:

An error occurred while installing mysql2 (0.4.4), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.4.4'` succeeds before bundling.  

Along with three other errors; see screenshot.

enter image description here

How do I make sure it succeeds before bundling during the deploy? Is there any files I need to look at to make sure I've done everything correctly? Let me know if I need to include any other files.

How to make charts in rails using csv/json files stored in database?

Posted: 30 Apr 2016 03:55 AM PDT

I have some csv/json data sets and a State (province of country) model in my appication. Now I wanna make another model Data and gonna relate it as follow :

state --> has_many:data

Data Model attributes must be the files in csv/json format My state model has one attribute :

name:string

now when the current user's location matches the state model's name string I want to show the graphs in the profile page of user the graphs must be from DATA model's(contains csv / json files).

Question 1: How do I store csv/json files in model ?

Question 2: How do I make charts using csv and json files contained in rails model ?

Beanstalkd BackBurner not starting

Posted: 30 Apr 2016 03:13 AM PDT

Whenever I am starting backburner I get following error but console shows daemon started successfully /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/generic.rb:214:in initialize': the scheme beanstalk does not accept registry part: : (or bad hostname?) (URI::InvalidURIError) from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:218:innew' from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:218:in parse' from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:747:inparse' from /Users/someuser/application/vendor/ruby/2.0.0/gems/backburner-0.4.6/lib/backburner/connection.rb:46:in `beanstalk_host_and_port'

Error when trying get index of list nested route Rails "unexpected tIVAR"

Posted: 30 Apr 2016 03:37 AM PDT

I want to get a list of all the reviews that belong to a, which belongs a category. I'm getting an error when trying to get a list of all the reviews in a JSON file (it's a API application): "/Code/Rails/videogame_reviews/app/controllers/reviews_controller.rb:6: syntax error, unexpected tIVAR, expecting '(' @reviews = @category.@game.reviews ^".

Could anybody explain why this is failing? @reviews = Reviews.all is working but shows all the reviews.

This the is ReviewsController

def index    @game = Game.find(params[:game_id])    @category = Category.find(params[:category_id])    @reviews = @category.@game.reviews    respond_to do |f|      f.html      f.json { render json: { category: @category, game: @game, reviews: @reviews} }    end  end  

I've made a copy from the GamesController index which is working

 def index    @category = Category.find(params[:category_id])    @games = @category.games    respond_to do |f|      f.html      f.json { render json: { category: @category, games: @games } }    end  end  

Here is the Reviews model

class Review < ActiveRecord::Base    belongs_to :game    validates_presence_of :comment  end  

This is the Game model

class Game < ActiveRecord::Base    belongs_to :category    has_many :reviews    validates_presence_of :title, :category  end  

And this is the Category model

class Category < ActiveRecord::Base    validates_presence_of :name    has_many :games  end  

Here is the routes for the reviews

resources :categories do    resources :games do       resources :reviews    end  end  

How to cache an array using Active Model Serializers (0.8)?

Posted: 30 Apr 2016 02:31 AM PDT

On an individual Active Model Serializer you can specify the cache key within your serializer, i.e.

Caching a single object using AMS

class OrgSerializer < ActiveModel::Serializer    cached     delegate :cache_key, to: :object  end  

Array caching

I need to deliver an array of these objects:

array_json = ActiveModel::ArraySerializer.new(Org.all.limit(50)).to_json  

Rather than do 50 cache hits to construct the array I want to do a single cache hit and expire it when any of the array elements expires.

How to cache the array (and construct the key)?

I therefore want a cache key for the array that is made up of the individual object IDs and their last-updated at date like this:

def cache_key_for_collection collection    keys = collection.collect{|element| "#{element.id}#{element.updated_at}" }    keys.join ""  end  

How can you do this with AMS (0.8)?

Does the AMS array serializer allow for this or is it something that needs to just be done manually? Is there a way to declare that you want caching and how the key should be constructed?

If it doesn't do it then what would be the neatest way to manually construct the cache/key?

awesome_nested_set (2.1.5) duplicate issue

Posted: 30 Apr 2016 02:27 AM PDT

awesome_nested_set gem is behaving weird, what I understand is lft and rgt values should be unique for each record. Otherwise tree structure will not be proper. However, I can see duplicate records within a table.

Below is the output of table.

select lft,rgt from groups where company_id=1;

Table Output

I want the values should be unique, I have checked for validation while inserting records, but awesome_nested_set gem updates the value for lft, rgt periodically hence the already existing data of records gets change. Not really sure how the gem internally works.

How can i use Soundmanager2 with ruby on rails

Posted: 30 Apr 2016 02:17 AM PDT

i'm a bit new to ruby on rails, i have uploaded the js scripts and the swf to my assets, i have also added the required lines to the appliction.js but when i put the script in my html.erb it does nt work Thanks in advance

Rails youtube thumbnail with scaffold

Posted: 30 Apr 2016 02:05 AM PDT

I have made a post scaffold . I want to extract the URL FROM the description column in which they can write anything including a youtube URL. Then I want to get a thumbnail place it with an image tag . and when people click on that image tag I want it to direct to the youtube URL

How To Convert Rails Application Into An Actual Site

Posted: 30 Apr 2016 01:52 AM PDT

I built a simple todo list application on Rails. I built it through Team Treehouse. It was one of the courses. I am wondering how would I convert it to a site. The reason being is because it would be a nice to add to my portfolio (I have yet to style it though). Would I simply upload the application to my github then go through such as I would to create a website through Github pages?

I plan to buy a url for it. I am just simply trying to gauge out how would I approach converting it into a site. My apologies, it is a noob question.

Ajax "link_to" sending multiple requests controller requests when clicked really fast(Rails 4)

Posted: 30 Apr 2016 02:25 AM PDT

Before I explain my problem, I will provide the relevant code for context. I have a Teams Model which is associated to a Scoreboard Model. The problem at hand is associated with Teams.

The View for Teams Index

<div class="team-list">      <%= render @scoreboard.teams.reject(&:new_record?) %>  </div>  

The Partial for @scoreboard.teams

<div class="row team-div" id="team_<%=team.id%>">      <div class="col-xs-3 team-div-1"> <%= team.name %> </div>         <%= link_to (edit_scoreboard_team_path(@scoreboard, team)), remote: true do %>         <div class="col-xs-6 team-data">          <div class="row">              <div class="col-xs-4 team-div-2"><%= team.win %> </div>              <div class="col-xs-4 team-div-2"><%= team.loss %> </div>              <div class="col-xs-4 team-div-2"><%= team.tie %></div>          </div>         </div>      <% end %>        <div class="col-xs-1 team-div-2">          <%= team.win + team.loss + team.tie %>      </div>        <div class="col-xs-1 team-div-2">        <% total_games = team.win.to_i + team.loss.to_i + team.tie.to_i %>      <% if total_games == 0 %>       <%= "N/A" %>      <% else %>       <%= (team.win.to_i/(total_games).to_f*100).round(2) %><%="%"%>      <% end %>      </div>        <div class="col-xs-1 team-setting">               <i class="fa fa-trash-o fa-lg" aria-hidden="true"></i>       </div>    </div>  

The link_to I'm having trouble with is for the Edit Method.

Team#edit Controller Method

  def edit      @scoreboard = Scoreboard.find(params[:scoreboard_id])      @team = @scoreboard.teams.find(params[:id])      respond_to do |format|       format.html {redirect_to scoreboard_url(@team.scoreboard_id)}       format.js       end     end  

The edit.js.erb file

$("#team_<%=@team.id%>").hide();  $("#team_<%=@team.id%>").before("<%= j render 'teamedit'%>");  

Now, to explain the problem.I am in the development environment. In a perfect world, I would like to click on the link_to for edit and have the specific team div disappear right away(only so I can't click on it again) and render the edit form for that Team. However, during slow loads(happens a lot), I can click on the link_to two or three times and it calls multiple controller requests to the edit method. The problem with this is that the Jquery is also executed as many times as I clicked and I end up with 2 or 3 forms for the same element.

For example, these are the log files when I click really fast on the link_to for Team with Id=50:

Started GET "/scoreboards/1/teams/50/edit" for 99.239.140.167 at 2016-04-30 08:07:52 +0000  Processing by TeamsController#edit as JS    Parameters: {"scoreboard_id"=>"1", "id"=>"50"}    User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    Scoreboard Load (0.3ms)  SELECT  "scoreboards".* FROM "scoreboards" WHERE "scoreboards"."id" = $1  ORDER BY "score oards"."created_at" DESC LIMIT 1  [["id", 1]]    Team Load (0.3ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."scoreboard_id" = $1 AND "teams"."id" = $2 LIMIT 1  [["scoreboard_id", 1], ["id", 50]]    Rendered teams/_teamedit.html.erb (3.1ms)    Rendered teams/edit.js.erb (7.1ms)  Completed 200 OK in 35ms (Views: 27.6ms | ActiveRecord: 1.2ms)      Started GET "/scoreboards/1/teams/50/edit" for 99.239.140.167 at 2016-04-30 08:07:52 +0000  Processing by TeamsController#edit as JS    Parameters: {"scoreboard_id"=>"1", "id"=>"50"}    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    Scoreboard Load (0.4ms)  SELECT  "scoreboards".* FROM "scoreboards" WHERE "scoreboards"."id" = $1  ORDER BY "scoreboards"."created_at" DESC LIMIT 1  [["id", 1]]    Team Load (0.3ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."scoreboard_id" = $1 AND "teams"."id" = $2 LIMIT 1  [["scoreboard_id", 1], ["id", 50]]    Rendered teams/_teamedit.html.erb (2.1ms)    Rendered teams/edit.js.erb (5.6ms)  Completed 200 OK in 30ms (Views: 24.2ms | ActiveRecord: 1.0ms)  

Each request rendered edit.js.erb so I ended up with two forms. How can I make it possible that no matter how many times I am able to click on the "link_to" before it disappears, only one edit-form for that resource is generated?

In Rails How to display errors in my comment form after I submit it?

Posted: 30 Apr 2016 07:01 AM PDT

I have a very straight-forward task to fulfil --- just to be able to write comments under posts and if the comments fail validation display error messages on the page.

My comment model uses a gem called Acts_as_commentable_with_threading, which creates a comment model after I installed.

On my post page, the logic goes like this:

Posts#show => display post and a form to enter comments => after the comment is entered, redisplay the Post#show page which has the new comment if it passes validation, otherwise display the error messages above the form.

However with my current code I can't display error messages if the comment validation fails. I think it is because when I redisplay the page it builds a new comment so the old one was erased. But I don't know how to make it work.

My codes are like this:

Comment.rb:

class Comment < ActiveRecord::Base    include Humanizer    require_human_on :create      acts_as_nested_set :scope => [:commentable_id, :commentable_type]      validates :body, :presence => true    validates :first_name, :presence => true    validates :last_name, :presence => true      # NOTE: install the acts_as_votable plugin if you    # want user to vote on the quality of comments.    #acts_as_votable      belongs_to :commentable, :polymorphic => true      # NOTE: Comments belong to a user    belongs_to :user      # Helper class method that allows you to build a comment    # by passing a commentable object, a user (could be nil), and comment text    # example in readme    def self.build_from(obj, user_id, comment, first_name, last_name)       new \          :commentable => obj,          :body        => comment,          :user_id     => user_id,          :first_name  => first_name,          :last_name   => last_name    end  end  

PostController.rb:

class PostsController < ApplicationController    before_action :authenticate_user!, except: [:index, :show]      def show        @post = Post.friendly.find(params[:id])        @new_comment = Comment.build_from(@post, nil, "", "", "")    end  end  

CommentsController:

class CommentsController < ApplicationController    def create      @comment = build_comment(comment_params)      respond_to do |format|          if @comment.save              make_child_comment              format.html              format.json { redirect_to(:back, :notice => 'Comment was successfully added.')}          else              format.html              format.json { redirect_to(:back, :flash => {:error => @comment.errors}) }          end      end  end    private      def comment_params          params.require(:comment).permit(:user, :first_name, :last_name, :body, :commentable_id, :commentable_type, :comment_id,              :humanizer_answer, :humanizer_question_id)      end        def commentable_type          comment_params[:commentable_type]      end        def commentable_id          comment_params[:commentable_id]      end        def comment_id          comment_params[:comment_id]      end        def body          comment_params[:body]      end        def make_child_comment          return "" if comment_id.blank?            parent_comment = Comment.find comment_id          @comment.move_to_child_of(parent_comment)      end        def build_comment(comment_params)          if current_user.nil?              user_id = nil               first_name =  comment_params[:first_name]              last_name = comment_params[:last_name]          else              user_id = current_user.id              first_name = current_user.first_name              last_name = current_user.last_name          end          commentable = commentable_type.constantize.find(commentable_id)          Comment.build_from(commentable, user_id, comment_params[:body],                      first_name, last_name)      end  end  

comments/form: (this is on the Posts#show page)

<%= form_for @new_comment do |f| %>      <% if @new_comment.errors.any? %>      <div id="errors">          <h2><%= pluralize(@new_comment.errors.count, "error") %> encountered, please check your input.</h2>            <ul>              <% @new_comment.errors.full_messages.each do |msg| %>                  <li><%= msg %></li>              <% end %>          </ul>      </div>    <% end %>  <% end %>  

How can I allow user put a website link into text_area and display the link that is clickable in Rails 4?

Posted: 30 Apr 2016 01:43 AM PDT

And user can put a description of the party. Also the user can type any link as description.

However, after user saved, the link he typed is not clickable. I have to copy the link address and paste into browser to go to the site.

Below is the views/parties/_form.html.erb:

<%= form_for(@party, multipart: true) do |f| %>    <div id="error_explanation">        <ul><%= @party.errors.full_messages.first if @party.errors.any? %></ul>    </div>      <div class="field">      <%= f.label :title %><br>      <%= f.text_field :title, :class => "form-control", placeholder: 'Type title' %>    </div>      <div class="field">      <%= f.label :location %><br>      <%= f.text_field :location, :class => "form-control", placeholder: 'Type location' %>    </div>      <div class="field">      <div class="form-group">          <label>time</label>          <%= f.datetime_select :time %>      </div>    </div>      <div class="field">      <%= f.label :description %><br>      <a style="text-decoration:none;" title="Suggest!" data-toggle="popover" data-trigger="hover" data-placement="top" data-content="Ticket? Any Link? Tell me more!"><%= f.text_area :description, :class => "form-control", :rows => "3" %></a>    </div>      <div class="field">        <%= f.label :image %><br>        <%= f.file_field :image %>    </div>    <p>    </p>    <div class="actions">      <%= f.submit "Let's post it", :class => "btn btn-primary", :id => "load", 'data-loading-text' => "Uploading...".html_safe %>    </div>    <p>    </p>  <% end %>  

How can I convert the link to clickable link if user typed any link? when show its description?

For example, if a user typed,  "Hi we have party tomorrow at 12:00 pm.  Also more information is at www.facebook.com/samplepartybrabrabra  ticket is $5 per person."  

Ruby on Rails where query with nesting relations

Posted: 30 Apr 2016 01:09 AM PDT

I learned how to use where query with relations from this question.

Ruby on Rails where query with relations

However, I still can't make it right with this nesting case. How can I make Summaries controllers index work?

Model

User    has_many :projects, dependent: :destroy    has_many :reasons, through: :projects    has_many :summaries, through: :projects, source: :reasons    has_many :entries, through: :projects    Project    belongs_to :user    has_many :reasons    has_many :entries, through: :reasons    Reasons    belongs_to :project    has_many :entries, dependent: :destroy     has_many :summaries, dependent: :destroy     Summary    belongs_to :reason    Entry    belongs_to :reason  

EntriesController

  # GET /entries    def index      entries     = current_user.entries      updated_at  = params[:updated_at]        # Filter with updated_at for reloading from mobile app      if updated_at.present?          # THIS WORKS!!!!!!!!!!!!!        entries = entries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i))        # Get all non deleted objects when logging in from mobile app      else        entries = entries.where(deleted: false)      end        render json: entries    end   

SummariesController

  # GET /summaries    def index      summaries   = current_user.summaries      updated_at  = params[:updated_at]        # Filter with updated_at for reloading from mobile app      if updated_at.present?              #THIS DOES NOT WORK, what can I do?????        summaries = summaries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i))            # Get all non deleted objects when logging in from mobile app      else        summaries = summaries.where(deleted: false)      end        render json: summaries    end    

@Error log on iOS

Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo={NSUnderlyingError=0x1481b9030 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"

@Error log on Heroku

[1m[36mUser Load (2.0ms)[0m [1mSELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1[0m 2016-04-30T07:48:18.909397+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms (ActiveRecord: 2.0ms) 2016-04-30T07:48:18.910250+00:00 app[web.1]: ActiveRecord::ConfigurationError (Association named 'reason' was not found on Reason; perhaps you misspelled it?):

Rspec tests are slower when I change the position of the validations in the model

Posted: 30 Apr 2016 12:34 AM PDT

I have a big rails application in which I have tons of models. I have reorganized the content of the models to follow a common pattern (positions of the fields, constants, relations, validations, hooks and so on on all files). After finishing of doing this process, I have realized that the tests are slower (a controller test which takes 40 seconds, now it uses more than 1 minute).

I have spent a lot of time trying to find the reason and finally I have found the problem. When I declare the validations after the relations, it takes more time to pass the tests (and the performarcen of the application is worse):

class Model    include Mongoid::Document      ## Fields    ...      ## Relations    ...      ## Validations    ...  end  

On the opposite, if I declare the relations after the validations, the performance is the same as previous:

class Model    include Mongoid::Document      ## Fields    ...      ## Validations    ...      ## Relations    ...  end  

I can't find a reason of this behaviour. Maybe it is because I am using mongoid 3 and this type of things are not happening with the next versions. However, for me it is more reasonable to have the relations before the validations because some of the validations reference to the relations.

calling function in rails

Posted: 30 Apr 2016 12:50 AM PDT

I try to use a function in Rails but I keep getting the same error. I tried a bit of everything!!

I define the function in my model. It is a big calculation but I completely simplified it too, and still get the same error!!

My function in my model: Original function:

class Customer < ActiveRecord::Base    belongs_to :partner      #    public      def find_next_user_value(user_sequence)     last_user_value = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.last_used }      user_prefix = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix }      user_length = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_length }      User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix } + number_to_string(User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.last_used } +=1).ljust(User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_length } - User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix }.bytesize,"0")    end  end  

Simplified version:

class Customer < ActiveRecord::Base    belongs_to :partner      #    public    def find_next_user_value      "TEST2"    end  end  

The call from the controller:

  def new     @customer = Customer.new(partner_id: @partner.id, customer_name: @partner.name, partner_number: @partner.number, number: @customer.find_next_user_value("Customer_Number"))    end  

simplified:

  def new      @customer = Customer.new(partner_id: @partner.id, customer_name: @partner.name, partner_number: @partner.number, number:  @customer.find_next_user_value)    end  

In both case I get the same error:

undefined method `find_next_user_value' for nil:NilClass

What am I doing wrong?

Thank you!!!!!

How to dynamically set the path of a link based on two different inputs?

Posted: 30 Apr 2016 12:51 AM PDT

I have a model Movie and I have a page for comparing two movies. I use params A and B to set the two movies:

<%    @movie1 = Movie.find_by(title: params[:A])    @movie2 = Movie.find_by(title: params[:B])  %>  

The left side of the page shows the "A" movie and the right side shows the "B" movie.

There's an option to remove the two current movies and input new ones. Right now the system I have is this: the "A" and "B" sides of the page both have a drop-down menu with clickable suggestions that come up as the user types, and clicking on a suggestion on the A side links to the same page except with params[:A] replaced, and vice versa.

For example, clicking on "Harry Potter" under the A side would use this link: <%= link_to "Harry Potter", compare_path(A: "Harry Potter", B: params[:B]) %>

But this way, the user has to wait for the page to load after selecting each movie. I want the user to be able to input both movies, and then press a button to reload the page with the new parameters.

So I would need some kind of "Run Comparison" link button, and clicking on a suggestion would have to reset that link's path, probably using jQuery. The trick is, the "A" suggestions would have to take into account the most recent "B" suggestion, and vice versa.

For example, if both selections are empty, and I select "Harry Potter" on the A side, then the link's path would be compare_path(a: "Harry Potter", b: ""), but then if I select "The Ring" on the B side, then the new path should be compare_path(a: "Harry Potter", b: "The Ring"). And then if I change my mind and select "Bewitched" on the A side, then the path is re-updated to compare_path(a: "Bewitched", b: "The Ring")

I'm completely lost. Anyone have any idea how to accomplish this?

Rails Routes - Id and name with spaces replaced with hyphens

Posted: 30 Apr 2016 04:02 AM PDT

I am developing my first application in rails. I went through the Rails Routing from the Outside In documentation but unable to figure out how to setup the following route.

I have a ClientsController and the for the show action I want to display the client's first and last name with spaces replaced with hyphens, in the url.

Instead of the following

localhost:3000/clients/1

the link should be (first name : john, last name : doe)

localhost:3000/clients/1/john-doe

Sum of all amount if charge dates are the same in Stripe

Posted: 30 Apr 2016 02:07 AM PDT

I'm iterating over a stripe charge object and I want to sum up the amount total for each day.

# Returns an array object of charges for a customer  @customer_charges = Stripe::Charge.all(:customer => current_user.stripeid)  

Views:

<% @customer_charges.map do |c| %>    On Monday, you were charged a total of <%= c.amount %>  <% end %>  

Surely the above does nothing more than output lines of each charges but not the sum for the day. The difficulty I face is to sum up all charges for each day. Could someone point me in the right direction?

The output would be like:

"On Monday, you were charged a total of 200000"  "On Tueesday, you were charged a total of 500000"  etc...  

Instead of:

On Monday, you were charged a total of 100000"  On Monday, you were charged a total of 100000"  etc...  

My view looks messy with lines of if statements to compare dates and that does not look right.

How much Rails knowledge do I need to develop a Shopify App?

Posted: 29 Apr 2016 11:50 PM PDT

Can I learn Ruby and Rails on Codecademy and build a Shopify App?

Advance Active Record Joins

Posted: 29 Apr 2016 11:39 PM PDT

I have the following models

Items   Customisations  Property Maps  

with Associations like so --

**Customizations**  belongs_to :item  has_many :property_maps, as: :mappable     **Items**    has_many :customizations    has_many :property_maps, as: :mappable    **Property Maps**  belongs_to :mappable, polymorphic: true  

I've implemented a pretty decent filtering system taking into consideration just Items and properties like so --

    def self.filter_in_properties(property_ids, group_name)             joins(:property_maps).joins('JOIN property_maps '+group_name+' ON '+group_name+'.mappable_id = items.id  AND '+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')')      end  

and I call them in the controller like so --

@items_without_pagination.filter_in_properties(params[:color_filter], 'color_filter').uniq  

How can I do build out a filtering system so that when for example a user searches for the color red, it not only returns items that have the property red but also return items which have customizations with the property red?

No comments:

Post a Comment