Sunday, December 11, 2016

How to add new Ruby environment in URU? | Fixed issues

How to add new Ruby environment in URU? | Fixed issues


How to add new Ruby environment in URU?

Posted: 11 Dec 2016 08:13 AM PST

I can register already installed a Ruby environment to URU by following command in terminal:

uru admin add c:\ruby-2.2\bin  

But, What is the way to install another ruby version in URU along existing one?

Rails: Attribute and method for two unrelated classes: Best DRY approach?

Posted: 11 Dec 2016 07:53 AM PST

This is an almost trivial problem but I want to follow (and learn more about) Rails best practices, in particular the DRY principle.

My app handles two unrelated classes, Countries and Places; both have an attribute name. In views, I use their name in titles etc., e.g. "Visit #{@country.name}".

In most instances, that works. But some Countries and Places require "the" as a prefix. Example: "Visit Netherlands" sounds clunky and wrong, so it must be "Visit the Netherlands". Yet in lists and search results, it is supposed to be "Netherlands", without "the".

If it were only one class that's affected, I would

  • add a boolean column prefix to its table
  • add a method called name_prefixed(uppercase=false) that would take name and, if prefix is true, prepend "the"/"The" (depending on the value of uppercase)
  • replace @country.name with @country.name_prefixed where applicable

However, since the issue exists with two unrelated classes, how would I best take care of this without repeating myself?

What is the best alternative for an application with multiple accesses to the database in Rails?

Posted: 11 Dec 2016 07:20 AM PST

I have some client applications that will make several restfull calls per second to my Rails application.

My restful service will basically be, find a user by id and update their data. But this will be done many times per second.

I am studying sql-caching and background jobs, but as I have little experience I do not know if this would solve my problem.

Thanks for the help.

Rails - is it possible to redirect to a custom path with params?

Posted: 11 Dec 2016 07:35 AM PST

So I am making an authorisation system. A new registration page is set to be '/signup'. If registration is invalid (username has already been taken, password too short), I want to show the errors. When I do it like this:

@user = User.create(user_params)      if @user.save          session[:user_id] = @user.id          redirect_to stories_path, notice: "Thanks for registration!"      else          render 'new'      end  

it works, but it renders in '/users' instead of '/signup'. And when instead of

render 'new'

I write

redirect_to '/signup'

it redirects, but errors are not shown. Is it possible to redirect to '/signup' and keep the errors?

user.rb:

class User < ActiveRecord::Base      has_secure_password      validates :username, presence: true, :uniqueness => { :case_sensitive => false }      validates :password, presence: true, :length => {minimum: 6}  end  

users_controller.rb:

class UsersController < ApplicationController      def new          @user = User.new      end        def create          @user = User.create(user_params)          if @user.save              session[:user_id] = @user.id              redirect_to stories_path, notice: "Thanks for registration!"          else              render 'new'          end      end        private        def user_params          params.require(:user).permit(:username, :password)      end  end  

new.html.erb:

<h3>New registration</h3>    <%= simple_form_for @user do |f| %>     <div> <%= f.input :username %>      <%= f.error :username %></div>      <div><%= f.input :password %>      <%= f.error :password %></div>        <%= f.button :submit %>  <% end %>  

and routes.rb:

Rails.application.routes.draw do    root 'stories#index'    resources :stories    resources :users    get 'signup' => 'users#new'  end  

Redirect from Rails controller after Angular POST

Posted: 11 Dec 2016 07:51 AM PST

I have a normal Rails app (no SPA) and on one page only I'm using Angular.
At the end I'm sending a POST to the server with the form data (and it is working) and as the final step of the POST I'd like to redirect to another page.

Rails controller is like this:

def save    data = params[:data]    respond_to do |format|      format.js { render :js => "window.location.href = '/products';" }    end  end  

But nothing is happening.

My Angular post is simple:

app.service('httpService', ['$http', function($http) {    this.post = function(data) {      $http({        method  : 'POST',        url     : '/cart/save',        data    : { data: data },        headers : {'Content-Type': 'application/json'}      });    };  }]);  

Calling service just like this, no promises:

this.save = function(ids) {    httpService.post(ids);  };  

Any ideas? Thanks.

EDIT:
I have tried also change the mime-type to 'application/javascript', but no success:

app.service('httpService', ['$http', function($http) {    this.post = function(data) {      $http({        method  : 'POST',        url     : '/cart/save',        data    : { data: data },        headers : {'Content-Type': 'application/javascript'}      });    };  }]);  

Strange issue with setting custom foreign_key

Posted: 11 Dec 2016 08:02 AM PST

From the documentation I read that:

class Book < ApplicationRecord    belongs_to :author, class_name: "Patron", foreign_key: "patron_id"  end  

so according to that I'm trying the next:

class Choco < ActiveRecord::Base    has_many :kinds, inverse_of: :choco, foreign_key: :myhash  

and

class Kind < ActiveRecord::Base    belongs_to :choco, foreign_key: :myhash  

But instead it pastes in that column NULL and I cannot understand why.

Schema

For Choco:

— (id, title, myhash)  

For Kind:

— (id, choco_id, title)  

I want to paste myhash on choco_id field on creating a new kind.

What is the problem?

Cucumber can not find the input or select the dropdown box well

Posted: 11 Dec 2016 06:48 AM PST

As usual, I use the fire-path to locate the element of my web application. However, my testing framework is cucumber+capybara. My web application is based on ruby on rails. Capybara support some high level keyword to do web application testing like "click_on", "select", "fill_in" and so on. The problems I met are:

  • One drop-down box id is "product_id" and one value is "TEST" However, the code like 'select "TEST", :from => "product_id' can not work. The step is passed, but the selection is not changed as expected.

  • one input '', I try to 'fill_in "clone-input", :with => "hello" but cucumber output one error like no filed 'clone-input' found. some my cucumber & capabara & rails gem versions are: cucumber (2.4.0) cucumber-api-steps (0.13) cucumber-core (1.5.0) cucumber-rails (1.4.5) cucumber-wire (0.0.1) capybara (2.0.3) jquery-rails (3.1.4) pry-rails (0.3.4) rails (3.2.22.2) rails-dom-testing (2.0.1) rails-html-sanitizer (1.0.3) rails-observers (0.1.2) rails_autolink (1.1.4)

How to fix the two issues? the fire-path can get the xpath, but the cucumber can not find them? why?

Rails 4: how to redirect_to a subdomain action

Posted: 11 Dec 2016 06:55 AM PST

In my rails 4 application I am trying to redirect to a controller action which is routed to a subdomain while passing some parameters to it.

Here is what works, but what needs some improvement:

redirect_to "http://subdomain.lvh.me:3000/build"  

As you can see, currently no paramters get passed to that url.
I'd like to pass (id: params[:id]).

I am wondering if there is a way to do this with the pathfinder as I am trying to access a subdomain action from my main domain.

Rails 5: link value from has_many table to belongs_to by ID

Posted: 11 Dec 2016 07:13 AM PST

I have has_many / belongs_to relationship:

models/media/media.rb

module Media    class Media < ApplicationRecord    has_many :positions, dependent: :destroy, inverse_of: :media, class_name: 'Position::Position'  end  

In Media::Media I have column name

models/position/position.rb

module Position    class Position < ApplicationRecord    belongs_to :media, optional: true, inverse_of: :position, class_name: 'Media::Media', foreign_key: 'media_id'  end  

In Position::Position I have column media_id.

I'm a bit stuck with relatively simple thing: how to show Media name for each position? Thank you for any help! I'm on Rails 5 and Postgresql 9.5.

Update

In console I try this: Position::Position.joins(:media).where(media_id: :id).select(:name) however I get this error: (Object doesn't support #inspect)

Testing mailer/ contact

Posted: 11 Dec 2016 06:49 AM PST

I created a movie review website which allows a logged in user to add, edit and delete a movie as well as leave reviews for each movie. I have also implemented a mailer for my contact form that sends a 'fake email' (displayed on the console only).

This is my first time working with Ruby so I am unsure on how to test my controller and method for contacts. Any form of advice will be much appreciated.

contacts_controller.rb:

class ContactsController < ApplicationController  def new   @contact = Contact.new  end    def create   @contact = Contact.new(params[:contact])   @contact.request = request     if @contact.deliver     flash.now[:notice] = 'Thank you for your message. We will contact you  soon!'    else     flash.now[:error] = 'Cannot send message.'     render :new      end   end  end  

contact.rb:

  class Contact < MailForm::Base    attribute :name,      :validate => true    attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.    attribute :message    attribute :nickname,  :captcha  => true     # Declare the e-mail headers. It accepts anything the mail method   # in ActionMailer accepts.   def headers    {     :subject => "My Contact Form",     :to => "your_email@example.org",     :from => %("#{name}" <#{email}>)    }    end  end  

routes:

 contacts    GET    /contacts(.:format)     contacts#new                   POST   /contacts(.:format)     contacts#create   new_contact GET    /contacts/new(.:format) contacts#new  

My testing so far:

require 'test_helper'    class ContactsControllerTest < ActionController::TestCase  include Devise::Test::ControllerHelpers    test "should get contact" do  get :new  assert_response :success     end  end  

rails project#index don't display user projects - Many to Many association

Posted: 11 Dec 2016 05:53 AM PST

I try to create app like this : An user can create a project, and invite many members to this project. Right now, I try to display all projects created by the user with projects#index method on projects_controller.rb. But, on browser, on /projects links, I don't have any errors, and don't have projects.

Here is my code,

projects_controller.rb :

 def index          @user = current_user          @projects = @user.projects      end    def create          @project = Project.new(project_params)          @project.user_id = current_user.id          if @project.save              flash[:success] = "successfully created project"              redirect_to projects_path          else              render 'new'          end      end  

Here is models (user, project, membership, invite) :

class Invite < ApplicationRecord      belongs_to :project      belongs_to :sender, :class_name => 'User'      belongs_to :recipient, :class_name => 'User'        before_create :generate_token       before_save :check_user_existence        def generate_token          self.token = Digest::SHA1.hexdigest([self.project_id, Time.now, rand].join)      end         def check_user_existence          recipient = User.find_by_email(email)          if recipient              self.recipient_id = recipient.id          end      end    end    class User < ApplicationRecord      has_many :memberships      has_many :projects, through: :memberships      has_many :invitations, :class_name => 'Invite', :foreign_key => 'recipient_id'      has_many :sent_invites, :class_name => 'Invite', :foreign_key => 'sender_id'    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end    class Project < ApplicationRecord      has_many :memberships      has_many :users, through: :memberships      has_many :invites  end    class Membership < ApplicationRecord      belongs_to :user      belongs_to :project  end  

And here is the view where I want to display user.projects :

<div class="container">      <h3> All your projects </h3>      <% @projects.each do |project| %>          <div class="project-card">              <div class="card-title">                  <%= link_to project.title, project_path(project) %>              </div>          </div>  <% end %>  </div>  

Maybe you want to see the schema :

ActiveRecord::Schema.define(version: 20161211133001) do      create_table "invites", force: :cascade do |t|      t.string   "email"      t.integer  "project_id"      t.integer  "sender_id"      t.integer  "recipient_id"      t.string   "token"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false    end      create_table "memberships", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"      t.integer  "project_id"      t.index ["project_id"], name: "index_memberships_on_project_id"      t.index ["user_id"], name: "index_memberships_on_user_id"    end      create_table "projects", force: :cascade do |t|      t.string   "title"      t.integer  "nb_team"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"    end      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end    end  

Thank you !

Devise. List of logged in

Posted: 11 Dec 2016 05:43 AM PST

Using devise for user login. Need to display list of currently signed in users. Have tried smth like:

User.find(0).user_signed_in?  

in the loop. Getting errors

Grey out div from toggle switch

Posted: 11 Dec 2016 06:04 AM PST

I am trying to to grey out a div based on whether a toggle is active(checked) or not. The js seems to be triggering when I select the toggle though the div isn't being faded out

Slim Template

- @products.each do |product|      .mdl-cell.mdl-cell--4-col.item-border.mdl-shadow--2dp        .mdl-cell.mdl-cell--1-col.mdl-cell--10-offset          label.mdl-switch.mdl-js-switch.mdl-js-ripple-effect for=product.name            input.mdl-switch__input checked="checked" type="checkbox" id=product.name /            span.mdl-switch__label        .mdl-cell.mdl-cell--12-col          h4.teal-heading= product.name        - @properties.each do |property|          .mdl-cell.mdl-cell--12-col            .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col              input.mdl-textfield__input type="text" id=property.id              label.mdl-textfield__label for=property.id                = "#{property.name } Price"  

Jquery

$('.mdl-switch__input').click(function(){ $(this).parent('.mdl-cell--4-col').$(this).fadeTo(500, 0.2); });  

Showing dynamically content in an efficient way, without using different template for every situation

Posted: 11 Dec 2016 05:24 AM PST

Best explained with an example:

Lets say I have many records, which I want to display in an html table. The columns which are shown are chosen before hand.

In this case,

user name (if @options[:user_name])

user email (if @options[:user_email])

sms phone (if @options[:user_email])

add new task (only if admin is not spectator)

Point is there are many different dynamic variables which decides which columns to show- Now this isn't a problem for the table header thead but It is a waste to ask the same questions and getting the same answers for every record (user)- there must be a better way.

I know I need to display the user_name, I don't want to ask if I need to for every user. But I can't make a different template for every combination of options etc'.

      <table>          <thead>            <tr>              <th>#</th>              <%= content_tag :td, 'User Name' if @options[:user_name] %>              <%= content_tag :td, 'User Email' if @options[:user_email] %>              <%= content_tag :td, 'Sms Phone' if @site.include_phone? %>              <% if admin? %>                <th>Actions</th>              <% end %>            </tr>          </thead>          <tbody>            <% @many_users.each.with_index(1) do |user, index| %>              <tr>                <td><%= index %>. </td>                <%= content_tag :td, user.name if @options[:user_name] %>                <%= content_tag :td, user.get_email_from_db(@options[:admin]) if @options[:user_name] %>                <%= content_tag :td, @site.get_phone(user) if @site.include_phone? %>                  <td class="actions">                  <%= link_to new_task_path(user_id: user.id) do %>new task<% end unless admin_is_spectator? %>                </td>              </tr>            <% end %>          </tbody>        </table>  

To summarize: How do I avoid asking the same ifs questions for which I know the answer before hand for every record?

How to format model ID in Rails?

Posted: 11 Dec 2016 05:43 AM PST

In Rails, How can I format output of model ID(auto increment primary key) from "12" to something like this "INV000012"

Thank you in advance.

Character count for text_area

Posted: 11 Dec 2016 04:58 AM PST

As I was trying to include a character count on my up I stumbled into this problem. Whilst I have managed to get it to display on my page I cannot see any number next to Character remaining, why is that happening?

Model

validates :project_description, presence: true, length: {minimum: 200 ,maximum: 850}  

Controller

def new    @project = Project.new    @maximum_length = Project.validators_on( :project_description ).first.options[:maximum]  end  

Form

<%= form_for(@project, html: { multipart: true }) do |f| %>   <%= render 'shared/error_messages', object: f.object %>    <%= f.text_area :project_description, placeholder: "In between 200 to 850 characters" %>         Chars remaining: <span id="counter" data-maximum-length="<%= @maximum_length %>"><%= @maximum_length %></span>         <br>          <span class="picture">         <%= f.label "Project banner (optional)" %>        <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>         </span>        <br>        <%= f.submit "Create", class: "btn btn-primary" %>      <% end %>        </div>     </div>    <script type="text/javascript">      $('#project_picture').bind('change', function() {      var size_in_megabytes = this.files[0].size/1024/1024;      if (size_in_megabytes > 5) {        alert('Maximum file size is 5MB. Please choose a smaller file.');      }    });       $(document).ready(function() {        var project_description = $("#project_description");        var counter     = $("#counter");        var maximum_length  = counter.data("maximum-length");          project_description.keyup(function() {            counter.text(maximum_length - $(this).val().length);        });        });  </script>  

There are no errors on the page and the console appears to render everything okay, any thoughts?

Thank you!

Rails Source Code - why wrapping class inside a class?

Posted: 11 Dec 2016 06:12 AM PST

I'm reading rails source code, and I can see in some code, instead of using the class directly, it's creating a sub-class. Example code:

# activesupport/lib/active_support/execution_wrapper.rb  class RunHook < Struct.new(:hook) # :nodoc:    def before(target)      hook_state = target.send(:hook_state)      hook_state[hook] = hook.run    end  end      # railties/lib/rails/application.rb  def initialize    # some code..    @executor          = Class.new(ActiveSupport::Executor)    @reloader          = Class.new(ActiveSupport::Reloader)    # some more code  end  

My questions is.. why it's needed use a subclass? Why not just use the class / struct directly?

Thanks.

Update: I've figured out the reason for the second example, it's because that ActiveSupport::Executor defines inherited methdod:

class << self # :nodoc:    attr_accessor :active  end    def self.inherited(other) # :nodoc:    super    other.active = Concurrent::Hash.new  end  

so whoever extends the class, would have active attribute defined with a new Concurrent::Hash.

However, I still don't quite understand why Struct needs to be extended.

Rails, Models, and "Projects" scoping

Posted: 11 Dec 2016 06:29 AM PST

I'm using Rails 5.0.0.1 and a custom authentication/authorization system (similar to Devise/CanCan).

I'm working on a Rails app and I'm looking for some advice on how to show/hide data based on whether or not a user is part of a "group" or "project".

The app: basically, users can "highlight" lines of a text article. They are first presented with a view of the article's contents (i.e., an index of its lines). They can select a line to highlight. When a line has been highlighted, any user can click on it to bring up a comments section for that line.

Article has_many Lines  Line has_many Highlights  Highlight has_many Comments  User has_many Highlights  User has_many Comments    Highlight belongs_to User  Comments belongs_to Highlight  Comments belongs_to User  

Now I would like to add "Group Project" functionality. A user selects an article to use in a Group Project. He invites other users to this project. Invited users can highlight and comment, but all the highlights and comments are only visible to users of that project.

My idea was to create 'scope'. By default, for all articles, highlights, and comments, the scope is 'public'. Any user can log in and view those articles, highlights, comments. But a user can also access one of his Group Projects and see (possibly the same) articles with 'privately' scoped highlights, comments, etc. This brings up the problem that a single Line can have multiple highlights and comments with different scopes. An article's line's highlights/comments have a single public version and multiple private versions.

My question is how can I efficiently deal with these multiple instances? Should I create new instances of the Lines for each project? This seems like unnecessary duplication in the database. Should I put some conditional in the controller or model to scope based on project_id or something similar?

I know there are multiple gems for dealing with "user groups", but they are typically used for authorization. I would like for a user to be able to create any number of projects, which each have their own invitees and highlights and comments.

save several data with single submit

Posted: 11 Dec 2016 04:19 AM PST

i have three models:

1) Product

class Product < ApplicationRecord      has_many :orders  end  

2) Shop

class Shop < ApplicationRecord      belongs_to :rayon      has_many :orders  end  

3) Order

class Order < ApplicationRecord      belongs_to :product      belongs_to :shop  end  

The Product model has these attributes:

  1. product_name
  2. product_type (With Ketchup / With Mayonnaise)
  3. product_size (Big / Small)
  4. expiration_date

Abbreviations for the table (= HTML ) which is used to take orders:

  • BSM => Big Sandwich with Mayonnaise
  • BSK => Big Sandwich with Ketchup
  • SSM => Small Sandwich with Mayonnaise
  • SSK => Small Sandwich with Ketchup

  • **qty => quantity

    <table border="1"> <tr> <th>Shop List</th> <th>BSM</th> <th>BSK</th> <th>SSM</th> <th>SSK</th> </tr> <tr> <td>Shop Name</td> <td>qty</td> <td>qty</td> <td>qty</td> <td>qty</td> </tr> Next shop, next order Etc... </table>

My question is how can I submit all these orders with single click in rails?

I hope, my question is clear. Thanks in advance.

No route matches

Posted: 11 Dec 2016 05:31 AM PST

Background

I have created a movie review app that allows a logged in user to add and edit a movie as well as leave a review for each movie.

Problem

I am working on testing my controllers, however I keep getting:

3) Error:   ReviewsControllerTest#test_should_get_edit:   ActionController::UrlGenerationError: No route matches   {:action=>"edit_movie_review", :controller=>"reviews"}   test/controllers/reviews_controller_test.rb:34:in `block in  <class:ReviewsControllerTest>'    4) Error:  ReviewsControllerTest#test_should_get_new:  ActionController::UrlGenerationError: No route matches {:action=>"new",    :controller=>"reviews"}  test/controllers/reviews_controller_test.rb:17:in `block in <class:ReviewsControllerTest>'      5) Error:  ReviewsControllerTest#test_should_show_review:  ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"reviews", :id=>"1"}  test/controllers/reviews_controller_test.rb:29:in `block in <class:ReviewsControllerTest>'        6) Error:  ReviewsControllerTest#test_should_create_review:  ActionController::UrlGenerationError: No route matches {:action=>"create", :controller=>"reviews", :review=>{:comment=>"MyText", :rating=>"1"}}  test/controllers/reviews_controller_test.rb:23:in `block (2 levels) in     <class:ReviewsControllerTest>'  test/controllers/reviews_controller_test.rb:22:in `block in <class:ReviewsControllerTest>'  

Rake routes:

                POST   /movies/:movie_id/reviews(.:format)          reviews#create     new_movie_review GET    /movies/:movie_id/reviews/new(.:format)      reviews#new     edit_movie_review GET    /movies/:movie_id/reviews/:id/edit(.:format) reviews#edit          movie_review GET    /movies/:movie_id/reviews/:id(.:format)      reviews#show                       PATCH  /movies/:movie_id/reviews/:id(.:format)      reviews#update                       PUT    /movies/:movie_id/reviews/:id(.:format)      reviews#update                       DELETE /movies/:movie_id/reviews/:id(.:format)      reviews#destroy                movies GET    /movies(.:format)                            movies#index                       POST   /movies(.:format)                            movies#create             new_movie GET    /movies/new(.:format)                        movies#new            edit_movie GET    /movies/:id/edit(.:format)                   movies#edit                 movie GET    /movies/:id(.:format)                        movies#show                       PATCH  /movies/:id(.:format)                        movies#update                       PUT    /movies/:id(.:format)                        movies#update  

ReviewsControllerTest:

require 'test_helper'    class ReviewsControllerTest < ActionController::TestCase    setup do    @review = reviews(:one)    @user = users(:one)  end    test "should get index" do    get :index    assert_response :success    assert_not_nil assigns(:review)  end    test "should get new" do    get :new    assert_response :success  end    test "should create review" do    assert_difference('Review.count') do     post :create, review: { comment: @review.comment, rating: @review.rating }    end   assert_redirected_to review_path(assigns(:review))   end    test "should show review" do    get :show, id: @review    assert_response :success  end    test "should get edit" do    get :edit_movie_review, @review    assert_response :success  end    test "should update review" do   put :update   assert_redirected_to review_path(assigns(:review))  end    test "should destroy review" do    assert_difference('Review.count', -1) do    delete :destroy, id: @review    end      assert_redirected_to reviews_path  end    end  

ReviewsController.rb:

class ReviewsController < ApplicationController   before_action :find_movie   before_action :find_review, only: [:edit, :update, :destroy]   before_action :authenticate_user!, only: [:new, :edit]     def new       @review = Review.new   end     def create      @review = Review.new(review_params)      @review.user_id = current_user.id      @review.movie_id = @movie.id         if @review.save #if a review is succesfully saved, redirect user to home           redirect_to movie_path(@movie)       else           render 'new'       end   end     def edit   end     def update       if @review.update(review_params)          redirect_to movie_path(@movie)       else            render 'edit'       end   end     def destroy       @review.destroy       redirect_to movie_path(@movie)   end      private      def review_params       params.require(:review).permit(:rating, :comment)    end      def find_movie       @movie = Movie.find(params[:movie_id])     end      def find_review       @review = Review.find(params[:id])    end  end  

I am new to the world of programming therefore any form of advice is much appreciated.

Thanks in advance!

AWS Rails install fails: activesupport requires Ruby version >= 2.2.2

Posted: 11 Dec 2016 04:08 AM PST

I am installing rails 5 on aws. I have installed rvm and ruby. Ruby version I installed is 2.3.1. I have done bundle install.

Now I am trying to install rails 5 by using command - 'sudo gem install rails --version 5.0.0'

But I am getting error

ERROR:  Error installing rails:          activesupport requires Ruby version >= 2.2.2.  

rvm list

=* ruby-2.3.1 [ x86_64 ]  

Complete log on running command - 'sudo gem install rails --version 5.0.0'

Fetching: i18n-0.7.0.gem (100%)  Successfully installed i18n-0.7.0  Fetching: thread_safe-0.3.5.gem (100%)  Successfully installed thread_safe-0.3.5  Fetching: tzinfo-1.2.2.gem (100%)  Successfully installed tzinfo-1.2.2  Fetching: minitest-5.10.1.gem (100%)  Successfully installed minitest-5.10.1  Fetching: concurrent-ruby-1.0.2.gem (100%)  Successfully installed concurrent-ruby-1.0.2  Fetching: activesupport-5.0.0.gem (100%)  ERROR:  Error installing rails:          activesupport requires Ruby version >= 2.2.2.  

Why it is showing ruby version required >= 2.2.2 ? What should I do here?

Country code validation with ISO

Posted: 11 Dec 2016 08:19 AM PST

I have in my model country code field. How can I validate if it is correct with ISO standards ?

Ruby on Rails - First argument in form cannot contain nil or be empty in Posts#show

Posted: 11 Dec 2016 02:33 AM PST

I've been making a blog system in Rails while learning the basics of Rails. However, I have encountered an error: "First argument in form cannot contain nil or be empty" in Posts' "show" view, as I want the comment form to be below the contents of the post. I have tried every solution to the problem including browsing other people's responses on Stack Overflow, however so far to no avail.

CommentsController.rb

class CommentsController < ApplicationController    def index      @comments = Comment.all    end      def new      @comment = Comment.new    end      def create      @post = Post.find(params[:comment[:id])      @comments = @post.comments.create(params[:comment])      if @comments.save        flash[:success] = "Your comment has been successfully created."        redirect_to @post      else        flash[:danger] = "Oops! Something went wrong!"        redirect_to @post      end    end      def edit     @comment = Comment.find(params[:id])    end      def update      @comment = Comment.find(params[:id])      if @comment.update_attributes        flash[:success] = "Your comment has been successfully updated."        redirect_to user_path      else        redirect_to user_path      end    end      def destroy      @comment = Comment.find(params[:id])      if @comment.destroy        flash[:success] = "Your comment has been successfully deleted."        redirect_to post_path      else        flash[:danger] = "Oops! Something went wrong. Try again."      end    end      private      def comment_params      params.require(:comment).permit(:content)    end    end  

show.html.erb (posts)

<div class="show_post">    <div class="container">      <div class="col-lg-9 col-md-9 col-sm-12 col-xs-12 col-lg-offset-3 col-md-offset-3">          <h2 class="heading">              <%= @post.title %>          </h2>            <%= raw(@post.content) %>      </div>        <div class="col-lg-9 col-md-9 col-sm-12 col-xs-12 col-lg-offset-3 col-md-offset-3">          <h4>              Liked this post? Add a comment below!          </h4>        <%= form_for(@comment) do |c| %> # Line that raises the error        <% if @comment.errors.any? %>          <div id="error_explanation">            <h2>              <%= "#{pluralize(@comment.errors.count, "error")} errors were detected in your form:" %>            </h2>       <ul>          <% @comment.errors.full_messages.each do |message| %>          <li>             <%= message %>         </li>          <% end %>       </ul>     </div>   <% end %>     <div class="form-group">      <%= c.label :content, "Your comment goes here: " %>      <%= c.cktext_area :content, rows: 10, class: "form-control" %>   </div>     <div class="form-group">      <%= c.submit "Add Comment", class: "btn btn-primary" %>   </div>    <% end %>   </div>        <div class="col-lg-9 col-md-9 col-sm-12 col-xs-12 col-lg-offset-3 col-md-offset-3">          <h3>              Comments:          </h3>              <% if @comments && @comments.any? %>                  <% @comments.each do |comment| %>                      <%= raw(comment.content) %>                  <% end %>              <% end %>      </div>  </div>  

routes.rb

Rails.application.routes.draw do    root 'pages#home'      get 'help' => 'pages#help'    get 'contact' => 'pages#contact'      get '/index' => 'users#index'    get '/signup' => 'users#new'    post '/users' => 'users#create'    get '/show' => 'users#show'      get '/login' => 'sessions#new'    post '/login' =>'sessions#create'    get '/logout' => 'sessions#destroy'      get '/new_post' => 'posts#new'    post '/new_post' => 'posts#create'    get '/show_post' => 'posts#show'    get '/delete_post' => 'posts#destroy'      resources :users      resources :posts     resources :comments  

I'm still a n00b in Rails, so I need help with solving this issue. Thanks in advance.

why is session not being set sometimes?

Posted: 11 Dec 2016 06:52 AM PST

I have a simple join room code for a multiplayer game.

The image below is the index page where the user first needs to type a name and then join the room.

enter image description here

Here two people join the room. One client is a chrome and another client is firefox. I did it so that two different sessions could be created.

enter image description here

After clicking join by both clients both click on join and they are taken to startgame page as shown below. The image below is a success scenerio since they both display their respective ids.

enter image description here

Most of the times, one id is missing. The error view is shown in the following image. I am wondering why is the id missing for one user or in other words why is the session not being set for one user. I have included below all the code of this simple application. I have been stuck on this issue for a while now so i am finally turning to stackoverflow for some directions. I appreciate your help a lot! Thanks! Often times the case is as follows. One id is missing for one client or user.

enter image description here The code is as follows:

class HelloController < ApplicationController        def index      end        def userCount            render plain: User.count        end          def join            n = params[:name]            u = User.create(name: n)            session[:current_user_id] = u.id              render plain: User.count        end              def startGame              @my_id = session[:current_user_id]          end      end  

The view files are as follows:

Index page(First page)

index.html.erb

<label> Status: </label>  <span id="status"> </span>        <br>  <br>      <input type="text" id="name"> </input>  <button id="join"> Join </button>  <br>  <button id="enterroom"> Enter Room </button>        <script>          var refreshId = setInterval(function() {          $.get( "/userCount", function( data ) {                $('#status').text(data);                });        }, 1000);            $( "#join" ).click(function() {          $.post( "/join", { name: $('#name').val() })        .done(function( data ) {              });          });            $( "#enterroom" ).click(function() {                window.location.replace("/startGame");      });            </script>  

The page after join is complete

startGame.html.erb

<h1> Ok game has started... </h1>    <br>    <h1> My id is <%= @my_id %> </h1>  

schema.rb

ActiveRecord::Schema.define(version: 20161211055722) do        create_table "users", force: :cascade do |t|      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end  

Routes

Rails.application.routes.draw do        root 'hello#index'        get '/userCount' => 'hello#userCount'      post '/join' => 'hello#join'      get '/startGame' => 'hello#startGame'    end  

UPDATE:

ok if i comment the following code in index.html.erb then the ids are generated everytime for both users. So, looks like the culprit is this section of code but i am confused why this is the case. The following code in index file is responsible for updating the total user count every 1 second. Could it be that when join is clicked a post request is prepared but this get call will intercept that call or void that call? Thanks!

/*  var refreshId = setInterval(function() {          $.get( "/userCount", function( data ) {                $('#status').text(data);                });        }, 1000);    */  

UPDATE2:

Ok i have verified that the session is being set in the join method but before the startGame method is executed, the session or session[:current_user_id] is being reset. I am wondering why is the session being reset at some point after the session is successfully set. Thanks!

UPDATE3:

class User < ApplicationRecord  end  

Capybara resets devise session after each request

Posted: 11 Dec 2016 12:44 AM PST

Code example:

login_as(user, scope: :user)  visit user_edit_path #this is authorized  # some expectations  visit user_comments_path #this is not authorized, return 401, why?  

But if I add second login_as after first visit - everything works. I don't know why devise session reseted. When I try to login through the login form via fill_in and click_on 'Log in', session reseted after redirect to root_path! So in that case i can't do even basic expectations that user was logged in. I tested on the different drivers.

Rspec configuration file:

# This file is copied to spec/ when you run 'rails generate rspec:install'  ENV['RAILS_ENV'] ||= 'test'  require File.expand_path('../../config/environment', __FILE__)  # Prevent database truncation if the environment is production  abort('The Rails environment is running in production mode!') if Rails.env.production?  require 'spec_helper'  require 'rspec/rails'  require 'capybara/rspec'  require 'capybara/poltergeist'    # NOTE: For Chrome support  Capybara.register_driver :selenium do |app|    Capybara::Selenium::Driver.new(app, :browser => :chrome)  end    # Capybara.register_driver(:poltergeist) { |app| Capybara::Poltergeist::Driver.new(app, js_errors: false) }  # Capybara.javascript_driver = :poltergeist    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }    # Checks for pending migration and applies them before tests are run.  # If you are not using ActiveRecord, you can remove this line.  ActiveRecord::Migration.maintain_test_schema!    RSpec.configure do |config|    config.include FactoryGirl::Syntax::Methods    config.include WaitForAjax    config.include FeatureHelpers    config.include Devise::TestHelpers, type: :controller    config.include Warden::Test::Helpers    config.extend ControllerHelpers,    type: :controller      # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures    config.fixture_path = "#{::Rails.root}/spec/fixtures"      # If you're not using ActiveRecord, or you'd prefer not to run each of your    # examples within a transaction, remove the following line or assign false    # instead of true.    config.use_transactional_fixtures = false      # RSpec Rails can automatically mix in different behaviours to your tests    # based on their file location, for example enabling you to call `get` and    # `post` in specs under `spec/controllers`.    #    # You can disable this behaviour by removing the line below, and instead    # explicitly tag your specs with their type, e.g.:    #    #     RSpec.describe UsersController, :type => :controller do    #       # ...    #     end    #    # The different available types are documented in the features, such as in    # https://relishapp.com/rspec/rspec-rails/docs    config.infer_spec_type_from_file_location!      # Filter lines from Rails gems in backtraces.    config.filter_rails_from_backtrace!    # arbitrary gems may also be filtered via:    # config.filter_gems_from_backtrace("gem name")    config.before :suite do      Warden.test_mode!    end  end  

How to authorize namespace, model-less controllers using CanCanCan?

Posted: 11 Dec 2016 12:17 AM PST

What is the correct way to authorize and check abilities for a namespaced, model-less controller using CanCanCan?

After much googling and reading the wiki, I currently have

#controllers/namespaces/unattacheds_controller.rb  def Namespaces::UnattachedsController    authorize_resource class: false    def create       # does some stuff    end  end    #models/ability.rb  def admin     can [:create], :namespaces_unattacheds  end    #view/  <%= if can? :create, :namespaces_unattacheds %>  # show a create form to authorized users  <% end %>  

This is not correctly authorizing the controller. Admins can see the conditional create form, but are not authorized to post to the create action.

post :create, valid_params  Failure/Error: { it { expect( flash ).to have_content "Successfully created" }   expected to find text "Successfully created"  got: "You are not authorized to access this page."  

In one example, the wiki suggests creating a separate Ability class for a namespaced controller. https://github.com/CanCanCommunity/cancancan/wiki/Admin-Namespace

Is there a simpler way to achieve this? This app uses many namespaced controllers, I don't really want to create an ability class for each one.

Is there correct syntax to refer to the namespaced controller in the Ability class?

can [:create], Namespaces::Unattacheds  can [:create], :namespaces_unattacheds  can [:create], namespaces/unattacheds  ????  

Ruby on Rails: save files in google drive

Posted: 10 Dec 2016 11:53 PM PST

I have a Ruby on Rail project but i need save files in an other folder, actually it is saving in a project default folder and the source is "app/public/system/.."

I'm trying save the files in google drive folder and i use: (this is my gemfile resume)

gem 'paperclip', '~>  5.1.0'  gem 'paperclip-googledrive-new'  gem 'google-api-client', '0.7.1', require: 'google/api_client'  

i did the following instructions to save my files: https://github.com/shoaibmalik786/paperclip-googledrive-new

My model is some like this:

has_attached_file :banner,           :storage => :google_drive,          :google_drive_credentials => "#{Rails.root}/config/google_drive.yml",          :google_drive_options => {              :public_folder_id => "0BxckPDmdZqdpYWgzbnVwUEhPVVU",              :default_image => "missing.png",               :path => proc { |style| "#{style}_#{id}_#{banner.original_filename}"          }      }  

i did the rake google_drive:authorize and didn't have errors and in my google_drive.yml i have the result.. is this :

client_id: <%= ENV["154813271628..."] %>  client_secret: <%= ENV["mOfV5821kUY..."] %>  access_token: <%= ENV["ya29.GlutA7bKMLwkHs6rXFYU92vZG..."] %>  refresh_token: <%= ENV["1/rAuECXRz..."] %>  

Also i used "active_admin" in my aplication The actually error in the aplication is this:

enter image description here

Thx for any help or more information

Whenever gem with cron or Resque gem for running tasks in rails

Posted: 11 Dec 2016 01:33 AM PST

I have a stock portfolio app that gets financial data from Yahoo Finance. I want to set up a feature that will calculate the portfolio's value (which will involve sending a get request to yahoo for all of the relevant stock prices and calculating the price * quantity and save that in the amount attribute of a portfolio object). I have a valuation model (that belongs_to a portfolio) that will be used to create valuation instances that will store the portfolio amount and date every day. I will then plot the portfolio's valuations on a graph to track the performance of it's stock picks.

I only want to run this once a day at the end of the day. As it stands now, I am thinking of simply using the whenever gem to schedule a task and run the above actions to fetch and calculate prices. Could this be a good use case for a background processing framework like Resque?

Heroku ActionController::Routing Error

Posted: 10 Dec 2016 11:45 PM PST

Im getting a strange routing when on Heroku but not locally, and I have no idea how to proceed with it. this is the error:

ActionController::RoutingError (No route matches [GET] "/authors/posts/this-is-just-a-test/publish"):

Routes:

 new_author_session GET    /authors/sign_in(.:format)             devise/sessions#new          author_session POST   /authors/sign_in(.:format)             devise/sessions#create  destroy_author_session DELETE /authors/sign_out(.:format)            devise/sessions#destroy         author_password POST   /authors/password(.:format)            devise/passwords#create     new_author_password GET    /authors/password/new(.:format)        devise/passwords#new    edit_author_password GET    /authors/password/edit(.:format)       devise/passwords#edit                         PATCH  /authors/password(.:format)            devise/passwords#update                         PUT    /authors/password(.:format)            devise/passwords#update                    root GET    /                                      blog/posts#index             edit_author GET    /author/:id/edit(.:format)             author#edit                  author GET    /author/:id(.:format)                  author#show                         PATCH  /author/:id(.:format)                  author#update                         PUT    /author/:id(.:format)                  author#update    publish_authors_post PUT    /authors/posts/:id/publish(.:format)   authors/posts#publish  unpublish_authors_post PUT    /authors/posts/:id/unpublish(.:format) authors/posts#unpublish           authors_posts GET    /authors/posts(.:format)               authors/posts#index                         POST   /authors/posts(.:format)               authors/posts#create        new_authors_post GET    /authors/posts/new(.:format)           authors/posts#new       edit_authors_post GET    /authors/posts/:id/edit(.:format)      authors/posts#edit            authors_post GET    /authors/posts/:id(.:format)           authors/posts#show                         PATCH  /authors/posts/:id(.:format)           authors/posts#update                         PUT    /authors/posts/:id(.:format)           authors/posts#update                         DELETE /authors/posts/:id(.:format)           authors/posts#destroy                   about GET    /about(.:format)                       blog/pages#about                 contact GET    /contact(.:format)                     blog/pages#contact                   write GET    /write(.:format)                       blog/pages#write                   posts GET    /posts(.:format)                       blog/posts#index                    post GET    /posts/:id(.:format)                   blog/posts#show  

post.rb

class Post < ApplicationRecord      extend FriendlyId       friendly_id :title, use: :slugged        belongs_to :author        scope :most_recent, -> {order(published_at: :desc)}       scope :published, -> {where(published: true)}        def should_generate_new_friendly_id?          title_changed?      end        def published_date           "Published on #{created_at.strftime("%-b, %-d, %-Y")}"      end    end  

routes.rb

devise_for :authors    root to: 'blog/posts#index'      resources :author, only: [:show, :edit, :update]    namespace :authors do       resources :posts do         put 'publish' => 'posts#publish', on: :member        put 'unpublish' => 'posts#unpublish', on: :member       end    end        scope module: 'blog' do        get 'about' => 'pages#about', as: :about          get 'contact' => 'pages#contact', as: :contact        get 'write' => 'pages#write', as: :write        get 'posts' => 'posts#index', as: :posts        get 'posts/:id' => 'posts#show', as: :post    end  

Following this post did not fix it.

Ruby on Rails 5: redirect_to giving url and path

Posted: 11 Dec 2016 01:04 AM PST

I am building a rails 5 web app. Everything is working great on my localhost development environment. I have a Digital Ocean dropplet (running Ubuntu 14.04, nginx/puma, and mySql). As per the normal sequence, after one logs in, I redirect to the root_path. Again on my localhost environment, this works as expected, but on the remote host (still under development environment) the redirect_to function gives both the url and the path.

here is my login controller code:

class SessionController < ApplicationController    def login      user = User.find_by_uname params[:uname]      if user.present?        @user = user.authenticate(params[:password])        if @user.present?          puts "@user present"          session[:userid] = @user.id          session[:uname] = @user.uname          @modal = 'login'          redirect_to root_path        else          puts "@user did not authenticate -- wrong password"        end      else        puts "#{params[:uname]} not in database."        render partial: 'utility/loginfailure', as: :js      end    end  end  

in the log/development.log file I see this:

Redirected to http://ruby.morgotha.net, ruby.morgotha.net/

From that it would seem to be coming from the redirect method, but it works fine on localhost dev.

I am not sure how to troubleshoot this anymore. So if someone is willing to guide me on digging into this a bit deeper, I sure would appreciate it.

Edit I changed the session controller to not need the return statement. The problem is still happening. root_path resolves to just "/".

No comments:

Post a Comment