Monday, June 13, 2016

RAILS Issue with User Cart | Fixed issues

RAILS Issue with User Cart | Fixed issues


RAILS Issue with User Cart

Posted: 13 Jun 2016 07:42 AM PDT

I've got a rails cart for a customer which works BUT only on the second attempt of trying to 'add-to-cart'. So everytime i click 'add to cart', the cart is empty the first time. But on second attempt, the item is added to cart. What am i doing wrong??

Here's the customer controller code

 class Customer::CartsController < ApplicationController     before_action :authenticate_user!     def show       @cart = if current_user       current_user.cart ||= Cart.find_by(session[:cart_id])       session[:cart_id] = nil if current_user.cart.purchased_at    end    if session[:cart_id].nil?      current_user.cart = Cart.create!(user_id: params[:id])      session[:cart_id] = current_user.cart.id     end    @cart = current_user.cart    end  end  

Regular Carts controller

 class CartsController < ApplicationController   skip_before_action :authorize, only: [:create, :update, :destroy]   before_action :set_cart, only: [:show, :edit, :update, :destroy]   rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart     def index    @carts = Cart.all   end    def show  end    def new   @cart = Cart.new  end    def edit  end    def create  @cart = Cart.new(cart_params)    respond_to do |format|    if @cart.save      format.html { redirect_to @cart, notice: 'Cart was successfully created.'}      format.json { render :show, status: :created, location: @cart }    else      format.html { render :new }      format.json { render json: @cart.errors, status: :unprocessable_entity }    end  end  end    def update    respond_to do |format|       if @cart.update(cart_params)         format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }         format.json { render :show, status: :ok, location: @cart }       else         format.html { render :edit }         format.json { render json: @cart.errors, status: :unprocessable_entity }       end      end     end     def destroy    @cart.destroy if @cart.id == session[:cart_id]    session[:cart_id] = nil   end   respond_to do |format|    format.html { redirect_to root_path, notice: 'Your Cart is currently empty.' }    format.json { head :no_content }   end  end    private    # Use callbacks to share common setup or constraints between actions.   def set_cart    @cart = Cart.find(params[:id])  end    # Never trust parameters from the scary internet, only allow the white list through.  def cart_params    params[:cart]  end    def invalid_cart    logger.error "Attempt to access invalid cart #{params[:id]}"    redirect_to root_path, notice: 'Invalid cart'  end  end  

Any help would be appreciated. Thanks in advance!

Pundit::NotDefinedError: unable to find policy when moving from Pundit 0.3 to 1.0

Posted: 13 Jun 2016 07:40 AM PDT

When I am running rspec wit pundit version 1.0 on one of my project spec classes I get multiple errors which I haven't seen before. However, when I'm switching to the previous version of pundit (0.3) everything works correctly.

Up to now what I have noticed is that with newer version of pundit @error in create function is not correctly assigned (instead of error class, I get an error message string from the error class).

class ErrorsController < ApplicationController    before_action :set_execution_environment      def authorize!      authorize(@error || @errors)    end    private :authorize!      def create      @error = Error.new(error_params)      authorize!    end      def error_params      params[:error].permit(:message, :submission_id).merge(execution_environment_id: @execution_environment.id)    end    private :error_params  

I have no idea what can cause my problem.

How to properly isolate multiple rails applications in development (local machine)

Posted: 13 Jun 2016 07:39 AM PDT

Given we use a preferred flavour of a ruby version manager (RVM or Rbenv) the ruby gems are isolated per ruby version.

  1. Let's say we want to work on multiple applications locally (they are completely separate applications) and we want to use the same ruby version and the same rails version how do we properly isolate them and their gems? Are gemsets the (only) answer here? I mean if I have 5 applications with the same ruby version and I keep adding gems on all 5 fronts it's just a matter of time when one of the applications is ok with the latest stable gem version while one of the apps will still need to roll on an older version of the same gem due to legacy dependency or whatnot. How do you guys avoid this timebomb?

  2. What if we want to use the same ruby version on multiple apps but a different Rails version? Rails being 'just a gem' is the answer same as for the above?

Thanks.

Rails: Retrieving DB records where attribute's parent meets criteria

Posted: 13 Jun 2016 07:27 AM PDT

I want to retrieve database records where an associated foreign entry's parent meets a certain criterion.

I have a Discipline model (for academic discipline). A Discipline can have another Discipline as a parent (e.g. "Social Sciences" would be the parent to "Anthropology"); there are only 2 levels, i.e. a Discipline with a parent cannot have children and vice-versa (ensured by the controller).

For clarity, let's call Disciplines without an assigned parent the Parent Disciplines, those with an assigned parent the Child Disciplines.

There is a Degree model. Each Degree is assigned a Child Discipline. E.g. a "BSc Anthropology" would be assigned to the "Anthropology" Discipline, never the "Social Sciences" Discipline directly.

Discipline:

class Discipline < ActiveRecord::Base    belongs_to :parent, class_name: "Discipline"    has_many :children, class_name: "Discipline", foreign_key: "parent_id"      has_many :degrees      ...  end  

Degree:

class Degree < ActiveRecord::Base    belongs_to :discipline      ...    end  

How do I now retrieve all the Degrees belonging to a certain Parent Discipline? Preferably I would like to avoid SQL code altogether and only use Rails code for it.

I'd guess this will go via a .join() but I cannot get my head around the logic I must apply here.

Thank you!

Query HSTORE key based on data type

Posted: 13 Jun 2016 07:25 AM PDT

Trying to use PostgreSQL HSTORE data structure. Users can add number of custom attributes for their records e.g:- source, counter_number, received_at etc.

Now we need to provide a filtering option based on the data type added. e.g:- received_at is datetime column so we will provide datetime specific filter.

If counter_number is integer then we will provide integer type filters.

Data type for every column is saved in separate table, that is used as reference while querying records.

Now if someone add string in datetime type field it will crash due to type conversion.

Is there a way to query in hstore that will query only records those are of some certain data type e.g:- Query only those rows those are having counter_number as integer.

How to force an html element to load first - RoR

Posted: 13 Jun 2016 07:23 AM PDT

Im have 2 drop down menus on my website that use the isotope plugin to filter items on the site. The problem is that those drop down menus take time to appear on the page, which is a problem especially on mobile devices because users might scroll down before they are even loaded and completely miss them. You can see the problem for yourself on my website www.shopwatchkw.com. The drop down menus are displayed in red and blue.

How can I make it so the two drop down menus either load faster or before the rest of the page is loaded so that users wont potentially miss it? I should point out that the options for the drop down menu are being populated through database requests from a Category and Mall model, and they are not static html text.

Here is the relevant code:

index.html.erb

<div class="filter-select">    <div id="filterGroup">      <select class="filter option-set selectpicker" data-filter-group="category" data-style="btn-category" data-size="false" title=" Choose a Category..">        <option data-filter-value="" selected="selected">All Categories</option>        <% @categories.each do |category| %>        <option data-filter-value=".category<%= category.id %>"><%= category.category_type %></option>        <% end %>       </select>        <select class="filter option-set selectpicker" data-filter-group="location" data-style="btn-location" data-size="false" title="Choose a Location..">       <option data-filter-value="" selected="selected">All Locations</option>       <% @malls.each do |mall| %>       <option data-filter-value=".mall<%= mall.id %>"><%= mall.name %></option>       <% end %>             </select>    </div>     </div>  

I'm not sure what other code would be useful but please let me know if you need more specific code.

Rails formatting logs to use with aws-logs and CloudWatch

Posted: 13 Jun 2016 07:18 AM PDT

AWS has this very cool log collection tool using aws-logs

However, I do not understand how I can format my log / configure the tool to be smarter and regroup the same error message. Right now AWS shows one message per line (because every line is timestamped)

enter image description here

My current log configuration indeed captures one new log entry per message. How can I go around it

[rails/production.log]  file = /var/www/xxx/shared/log/production.log  log_group_name = /rails/production.log  log_stream_name = {instance_id}  time_zone = LOCAL  datetime_format = %Y-%m-%dT%H:%M:%S  

Is there any software out there to visually represent the branches, directories and tags created as I develop a Ruby on Rails program?

Posted: 13 Jun 2016 07:11 AM PDT

I am looking for software to illustrate all the directories and branches I have created during a Ruby on Rails program but cannot find any. I feel it would be really useful to have a graphical representation of what branch/directory I am currently in relative to the others etc. Also to have an illustration of the various tags and versions I have created and be able to click back and forth between them. Does anyone else think this would be useful at all?? And if software like this exists could you post a link? Thanks in advance.

Ruby on Rails Tab

Posted: 13 Jun 2016 07:22 AM PDT

I have the below HTML for Tabs using Bootstrap. Now I want to click on particular tab and show data related to that tab. How can I do that

All order

Internet

Telephone

Cellphone

Cable

Bundle

Create object in Rails from text file

Posted: 13 Jun 2016 06:57 AM PDT

I am building a site with Ruby on Rails where I can display items that are for sale. Currently I can add new items by filling a form with title, price, some text and upload a couple of pictures.

Since there might be many items I would like to have a text file with the data, one item on each line, data separated with comma or whatever. Then I'd like to give this file to my Rail's application that will create the items in the application. Would this be possible?

Rails Action Cable + Angular JS

Posted: 13 Jun 2016 06:45 AM PDT

I have grape api and angular js application. I have integrated action cable over here and stuck at some problem.

This is my plugin https://github.com/wazery/ngCable

I run websocket within Puma server through rails s Puma.

=> Booting Puma  => Rails 4.2.6 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Puma starting in single mode...  * Version 3.4.0 (ruby 2.3.0-p0), codename: Owl Bowl Brawl  * Min threads: 0, max threads: 16  * Environment: development  * Listening on tcp://localhost:3000  

My routes in config/routes.rb

  mount ActionCable.server => '/cable'  

cable/config.ru

run ActionCable.server  

config/redis/cable.yml

local: &local     :url: redis://localhost:6379     :host: localhost     :port: 6379     :timeout: 1     :inline: true  development: *local  test: *local  

channels/messages_channel.rb

class MessagesChannel < ApplicationCable::Channel    def subscribed      stream_from('messages')    end  end  

channels/application_cable/channel.rb

module ApplicationCable    class Channel < ActionCable::Channel::Base    end  end  

channels/application_cable/connection.rb

module ApplicationCable    class Connection < ActionCable::Connection::Base    end  end  

I have done all configs through the whole documentation, leading by this article https://blog.heroku.com/archives/2016/5/9/real_time_rails_implementing_websockets_in_rails_5_with_action_cable

But I am getting right now...

Started GET "/cable" for 127.0.0.1 at 2016-06-13 16:04:13 +0300  Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-06-13 16:04:14 +0300  Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-06-13 16:04:14 +0300  MessagesChannel is transmitting the subscription confirmation  MessagesChannel is streaming from messages    Rendered shared/_header.html.slim (11.3ms)    Rendered shared/_footer.html.slim (5.0ms)  Completed 200 OK in 2176ms (Views: 2161.0ms | ActiveRecord: 0.0ms)  Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-06-13 16:04:15 +0300  MessagesChannel stopped streaming from messages  

Here is my submit.

  $scope.messages = [];    $scope.message = {};    $scope.save = function() {      AccountsMessages.save({          conversation_id: $stateParams.conversation_id,          message: $scope.message        },        function(response) {          var cable = $cable('ws://localhost:3000/cable');          var channel = cable.subscribe('MessagesChannel', {            received: function(response) {              $scope.messages.push(response);            }          });          $state.transitionTo('messages_index', {            conversation_id: $stateParams.conversation_id          })          $scope.message = {};        },        function(errors) {          $scope.errors = errors;        }      );    };  

Thanks.

Error with Rails Mailer

Posted: 13 Jun 2016 06:31 AM PDT

I've written a code so that the attendees of a conference receive an email whenever a call is made. My mailer code is this:

def send_attendee_invite(conference_id)  # Setting value for attendees which is an array of user type  @attendees.each do |attendee|    @attendee = attendee    subject = "Some Subject specific to attendee"    mail.attachments['attachment.ics'] = { mime_type: 'text/calendar', content: someattachment}    mail(to: @attendee.email, subject: subject)  end end  

The test I've written for this is:

test "mail to an attendee for a conference" do    conference = conferences(:test)    email = ABCMailer.send_attendee_invite(conference.id).deliver_now    assert_not ActionMailer::Base.deliveries.empty?    assert_equal [Settings.mail.default_from], email.from    assert_equal ["attendee_1@mail.com"], email.to    assert_includes email.body.encoded, "You have been invited to a conference call scheduled by Requesor." end  

Mail goes to attendee_1's email but has the following body

\r\n----==_mimepart_575ea732df68e_144d8df98c2091b\r\nContent-Type: text/plain;\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n<p></p>Hi Attendee_2, <p></p>You have been invited to a conference call scheduled by Requestor. <p></p>The invite has been attached in this email. You can download and add it to your calendar.\r\n\r\n\r\n----==_mimepart_575ea732df68e_144d8df98c2091b\r\nContent-Type: text/html;\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n<html>\r\n  <body>\r\n  <p></p>Hi Attendee_2, <p></p>You have been invited to a conference call scheduled by Requestor. <p></p>The invite has been attached in this email. You can download and add it to your calendar.\r\n </body>\r\n</html>\r\n\r\n----==_mimepart_575ea732df68e_144d8df98c2091b\r\nContent-Type: text/html;\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n<html>\r\n  <body>\r\n  <p></p>Hi Attendee_2, <p></p>You have been invited to a conference call scheduled by Requestor. <p></p>The invite has been attached in this email. You can download and add it to your calendar.\r\n </body>\r\n</html>\r\n\r\n----==_mimepart_575ea732df68e_144d8df98c2091b\r\nContent-Type: text/html;\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n<html>\r\n  <body>\r\n  <p></p>Hi Attendee_2, <p></p>You have been invited to a conference call scheduled by Requestor. <p></p>The invite has been attached in this email. You can download and add it to your calendar.\r\n </body>\r\n</html>\r\n  

The html.slim page is being called thrice instead of once and so the body appears three times in the same email.

Secondly, for some reason, instead of sending two emails for two attendees, it sends one email to attendee_1's email id with the body that must appear in attendee_2's email. Attendee_2 doesn't get his own email at all.

I'm calling this mailer this way:

ABCMailer.send_attendee_invite(conference.id).deliver_now  

Can anyone please help?

Algolia rails Invalid index/slave name error

Posted: 13 Jun 2016 06:54 AM PDT

I have two master indexes(Content,SubContent) with four slave indexes each. When i tried

Content.raw_search "", slave: ""  

works fine.

SubContent.raw_search "", slave: "Latest"  

also works fine.

SubContent.raw_search "", slave: ""  # > ArgumentError: Invalid index/slave name:   

Is there any mistakes on my side?

How to disable / stub out any Rails ActiveRecord call for one test

Posted: 13 Jun 2016 06:30 AM PDT

Let say I'm replacing functionality in Ruby on Rails of particular piece of code from ActiveRecord::Base functionality to ElasticSearch object model (So that no PostgeSQL / MySQL / SQL is called when hitting that object is called. E.G. serializer for search endpoint /works/search

So how to ensure in RSpec that no SQL call is made when retrieving data (e.g. test will raise exception if SQL call was made via ActiveRecord)

Create a nested form : "undefined method `push'"

Posted: 13 Jun 2016 06:17 AM PDT

I would like to build a new Review form, but it return me an error than I don't understand. Con you explain me the problem ?

My code

routes :

resources :posts do       resources :pushs do         resources :reviews      end     end   

The link :

<%= link_to 'Add comment', new_post_push_review_path(@push.post_id, @push) %>  

The form that I would like to built :

<%= simple_form_for([@post, @post.push.reviews.build]) do |f| %>    <%= f.input :rating %>  <%= f.input :comment %>  <%= f.button :submit %>    <% end %>  

enter image description here

& finally, the controller review :

class ReviewsController < ApplicationController    before_action :authenticate_user!    before_action :find_push    before_action :find_post            def new       @review = Review.new       @pushs = Push.all    end       def create      @push = Push.find(params[:review][:id])      @review = Review.new(review_params)         @review.post_id = @push.post_id       @review.push_id = @push.id        @review.user_id = current_user.id        if @review.save         redirect_to push_path(@push.post_id, @push)      else         render 'new'      end     end     private       def review_params      params.require(:review).permit(:rating, :comment)    end            def find_post      @post = Post.find(params[:post_id])    end       def find_push      @post = Post.find(params[:post_id])      @push = @post.pushs.find(params[:push_id])     end     end  

Well, if you have any ideas to explain me my error(s), that would be great !!

call different controller via RestClient in rails?

Posted: 13 Jun 2016 05:49 AM PDT

Hi I'm developing apis for my rails app, my rails app will act like a sever for those who call these apis.

I have built an api which gives the roles present in database. When I hit this url on the browser http://localhost:3000/apis/roles it is working fine but when I'm calling it from my controller the code stops execting and the page keeps on loading

below is my code

 def new        uri = "http://localhost:3000/apis/roles"  # controller => apis/roles , action => index        response = RestClient.get uri # code stops here         debugger         render json: {          message: "hello users"        }    end  

when I press Clt+c to stop the server I'm getting this issue ThreadError: Attempt to unlock a mutex which is locked by another thread

any Idea why I'm getting this

How to customize rails_admin navigation(side bar)?

Posted: 13 Jun 2016 06:21 AM PDT

I've been working on rails_admin and have many models in my project, In navigation all the models are displaying, need to scroll down for all models, So I want to display the models based on some group (main menu under that sub-menu's like in active admin). But rails_admin I don't find an option to that.I Need help.

js post data to rails & refreshing view

Posted: 13 Jun 2016 06:43 AM PDT

I have a problem (oh no). With rails I'm showing table which is sortable, I move the line, ajax posts data (which line to where) to rails controller, which saves data to DB (render :nothing => true).

Now I wish to reload the page as new calculation should occur. If I use reload in js (success: window.location.reload();) page reloads but with old data. I used also delay (setTimeout(,.., 1000)) without success.

It seems as data is not yet in DB.

How can I reload in rails controller where the data was POST. Or maybe other solution.

LP dejan

How to remove column created by paper clip

Posted: 13 Jun 2016 06:48 AM PDT

I created an attachment field with paperclip using migration.

rails g migration paperclicp user photo  

Now I want to remove the photo column from users table now. I tried following

class RemoveAttachmentPhotoToUser < ActiveRecord::Migration    def change      remove_column :users, :photo_file_name      remove_column :users, :photo_content_type      remove_column :users, :photo_file_size      remove_column :users, :photo_updated_at      remove_column :users, :photo_updated_at    end  end  

and also tried this

class RemoveAttachmentPhotoToUser < ActiveRecord::Migration    def change      remove_attachment :users, :photo    end  end  

and this

rake db:migrate:down VERSION=XXXX  

The error I get is

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    11111111111 is out of range for ActiveRecord::Type::Integer with limit 4/home/bcc/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.5/lib/active_record/type/integer.rb:45:in `ensure_in_range'  

Transaction doesn't work in a Rails migration

Posted: 13 Jun 2016 05:23 AM PDT

I created a migration with transaction on multiple models:

  def up      add_column :questionnaires, :backup, :boolean, default: false      add_column :questionnaire_steps, :backup, :boolean, default: false        ActiveRecord::Base.transaction do        Questionnaire.where(backup: false).each do |questionnaire|          questionnaire_backup = questionnaire.dup          questionnaire_backup.assign_attributes(backup: true)          questionnaire_backup.save!            questionnaire.questionnaire_steps.each do |step|            step_backup = step.dup            step_backup.assign_attributes(              backup: true,              questionnaire_id: questionnaire_backup.id            )            step_backup.save!          end            questionnaire.questionnaire_runs.each do |run|            run.update_attributes!(questionnaire_id: questionnaire_backup.id)          end        end      end    end  

The problem is, that it doesn't work. Some of QuestionnaireRuns in a database are invalid and it raises an exception. I hoped that all changes (creation of Questionnaires and QuestionnaireSteps) will be reverted because of this exception. But it didn't happen. Why is that?

Overriding Spree views with deface

Posted: 13 Jun 2016 05:09 AM PDT

I have a spree view I want to override with deface. It consists of three li tags. I want to insert one more li at the top of remaining li's.

The view I want to override is:

spree/admin/orders/cart.html.erb    <% content_for :page_actions do %>   <% if can?(:fire, @order) %>      <li><%= event_links %></li>   <% end %>  <% if can?(:resend, @order) %>      <li><%= button_link_to Spree.t(:resend), resend_admin_order_url(@order), :method => :post, :icon => 'email' %></li>  <% end %>  <% if can?(:admin, Spree::Order) %>      <li><%= button_link_to Spree.t(:back_to_orders_list), admin_orders_path, :icon => 'arrow-left' %></li>  <% end %>  

What I wrote to override this is:

Deface::Override.new(  :virtual_path => "spree/admin/orders/cart",  :name => "fraud_email_for_order",  :insert_before => "li:first",  :partial => "spree/admin/orders/send_fraud_email",  :disabled => false)  

What this does is inserts an li before every one of three li's. I can't figure out why is that? li:first seems a reasonable css selector to do this. I tried replacing insert_before with insert_top but in vain. Can anybody tell me what's happening and how to rectify it? Any help will be appreciated.

wrong response status in rspec + devise + factory_girl

Posted: 13 Jun 2016 06:13 AM PDT

so i've been trying to make a basic response test - with 200 and 403. I'm not sure i need to add anything else ..

accounts_spec.rb

RSpec.describe Api::V1::AccountsController, :type => :controller do    describe "GET index no account" do      it "has a 403 status code" do        get :index        expect(response.status).to eq(403)      end    end    describe "GET index with account" do      login_user      it "has a 200 status code" do        get :index        expect(response.status).to eq(200)      end    end  end  

Accounts Controller #index

def index      #show user details      raise if not current_user      render json: { :user => current_user.as_json(:except=>[:created_at, :updated_at, :authorization_token, :provider, :uid, :id])}      rescue      render nothing: true, status: 403     end  

I keep getting

1)Api::V1::AccountsController GET index with account has a 200 status code  expected: 200  got: 403  

Any thoughts on where i'm doing it wrong ?

UPDATE

module ControllerMacros    def login_user      before(:each) do        @request.env["devise.mapping"] = Devise.mappings[:user]        user = FactoryGirl.create(:user)        sign_in :user, user      end    end  end  

How to display only non-persised data in case of validation error in Rails 4?

Posted: 13 Jun 2016 04:43 AM PDT

When validation error (for example, wrong email format) occurs, all previously saved users of the same tenant are also displayed as a result of render 'new' in TenantController. How can I display only that one for whom validation error was generated? I tried to add <% if !u.object.persisted? %> to signup form:

  <%= f.fields_for(:users) do |u| %>      <% if !u.object.persisted? %>      ...      <% end %>    <% end %>  

In this case the form is displayed correctly, BUT when I correct the validation error (for example, enter correct email) and press Save button, then update action is executed, not create action. This is wrong because there is nothing to update yet.

Tenant model:

class Tenant < ActiveRecord::Base      has_many :users, dependent: :destroy, inverse_of: :tenant    accepts_nested_attributes_for :users          before_validation do       self.status = 0       self.name = name_orig.upcase       email.downcase!    end      validates :name_orig, presence: true, length: { maximum: 255 }      validates :name, uniqueness: { case_sensitive: false }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i    validates :email, presence: true, length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }      validates :status, presence: true    end  

User model:

class User < ActiveRecord::Base      belongs_to :tenant, inverse_of: :users      before_validation do       self.status = 0      self.email = email.downcase    end      validates :tenant, presence: true      VALID_USERNAME_REGEX = /\A\w+\s?\w*\z/i    validates :name,  presence: true, length: { maximum: 50 },                      format: { with: VALID_USERNAME_REGEX },                      uniqueness: { case_sensitive: false }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i    validates :email, presence: true, length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }      has_secure_password    validates :password, presence: true, length: { minimum: 6 }      validates :status, presence: true    end  

Tenant controller:

class TenantsController < ApplicationController      def show      @tenant = Tenant.find(params[:id])    end      def new      @tenant = Tenant.new      @tenant.users.build    end      def create      @tenant = Tenant.find_by(name: tenant_params[:name_orig].upcase)      if @tenant == nil        @tenant = Tenant.new(name_orig: tenant_params[:name_orig],                              email: tenant_params[:email])        @user = @tenant.users.build(tenant_params[:users_attributes]["0"])        @tenant.save        if @tenant.save          flash[:success] = "Welcome!"          redirect_to @user   # redirects to user profile        else          render 'new'        end      else        @user = @tenant.users.build(tenant_params[:users_attributes]["0"])        if @user.save          flash[:success] = "Welcome!"          redirect_to @user   # redirects to user profile        else          render 'new'        end      end    end         private        def tenant_params        params.require(:tenant).permit(:name_orig, :email,            users_attributes: [:name, :email, :password, :password_confirmation])      end  end  

Signup form:

<%= form_for(@tenant) do |f| %>      <%= render 'shared/tenant_error_messages' %>      <%= f.label :name_orig, "Company name" %>    <%= f.text_field :name_orig, class: 'form-control' %>      <%= f.label :email, "Company e-mail" %>    <%= f.email_field :email, class: 'form-control' %>      <%= f.fields_for(:users) do |u| %>        <%= u.label :name, "User name" %>      <%= u.text_field :name, class: 'form-control' %>        <%= u.label :email, "User e-mail" %>      <%= u.email_field :email, class: 'form-control' %>        <%= u.label :password, "Password" %>      <%= u.password_field :password, class: 'form-control' %>        <%= u.label :password_confirmation, "Password confirmation" %>      <%= u.password_field :password_confirmation, class: 'form-control' %>      <% end %>      <%= f.submit "Save", class: "btn btn-primary" %>  <% end %>  

Issue with form_tag in rails

Posted: 13 Jun 2016 05:47 AM PDT

I am using form_tag in my create.html.erb file. Under this form_tag there is a button. Now I wish that after clicking the button the page will be refreshed only ,I dont want to redirect anywhere . So what should I write in my form tag as path?

For session controller my view/sessions/create.html.erb file is:

<h4>Database contents here:</h4>    <table>                             <tr>        <th>ID</th>                              <th>AGE</th>      <th>NAME</th>    </tr>    <% @data.each do |data| %>             <tr>        <td><%= data.id %></td>          <td><%= data.age %></td>          <td><%= data.name %></td>       </tr>    <% end %>                          </table>     <div>    <%= form_tag :method => :get do %>      <%= button_tag type: 'submit'  do %>        <%= content_tag :div do%>          <h4>View Data </h4><h4><%= @num %></h4>       <% end %>      <% end %>    <% end %>  </div>  

And my contollers/sessions_controller file is:

class SessionsController < ApplicationController    def new    end      def index    end      def create      user = User.authenticate(params[:email], params[:password])      @data=Information.all      @num=Information.count()      @tym=Time.now.getutc      if user        session[:user_id] = user.id        #redirect_to root_url, :notice => "Logged in!"          #this part is for showing the content of the information table            respond_to do |format|          format.html          format.xml { render xml: @data }        end      else       flash.now.alert = "Invalid email or password"       render "new"      end    end      def destroy      session[:user_id] = nil      redirect_to root_url, :notice => "Logged out!"    end  end  

How to implement MediumEditor gem within SimpleForm in Rails?

Posted: 13 Jun 2016 05:53 AM PDT

I want to add MediumEditor to a simple form field where users are able to write texts. There is a gem for rails but I don't know how to implement it within a simple form.. How the f.input field should look?

Build a second step of a nested form?

Posted: 13 Jun 2016 05:54 AM PDT

I try to build a nested form with two bearing (= post do push do reviews) And I have this error :

Error generated

I would like to know if I have the good practices to succeed this creation ?

My code

Views/pushs/show:

<%= link_to 'Add comment', new_post_push_review_path(@push.post_id, @push) %>  

Reviews/controller :

class ReviewsController < ApplicationController    before_action :authenticate_user!    before_action :find_post    before_action :find_push      def new       @review = Review.new     end       def create      @review = @post.push.reviews.create(review_params)       @review.post_id = @push.post_id      @review.push_id = @push.id       @review.user_id = current_user.id        if @review.save         redirect_to push_path(@push.post_id, @push)      else         render 'new'      end     end       private       def review_params      params.require(:review).permit(:rating, :comment)    end       def find_post      @post = Post.find(params[:post_id])    end       def find_push      @post = Post.find(params[:post_id])      @push = Push.find(params[:push_id])    end     end  

Views/reviews/new:

<%= simple_form_for([@post, @post.push.reviews.build]) do |f| %>    <%= f.input :rating %>    <%= f.input :comment %>    <%= f.button :submit %>  <% end %>  

& the routes :

resources :posts do     resources :pushs do       resources :reviews    end   end   

Deploying with Capistrano, nginx and puma

Posted: 13 Jun 2016 06:28 AM PDT

I followed this tutorial: https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma

to learn how to deploy my project to a staging environment

everything works great except the server won't restart after I deploy and still runs on the old version.

  1. I'm running the staging environment from the /current deployed folder, by using "rails s -e staging"
  2. I'm running sidekiq, redis and another task using "RAILS_ENV=staging foreman start"
    1. deploying using "cap staging deploy" from my development project folder

am I doing anything wrong? This project was passed to me by another team and I can't contact them for questions so there may be information missing here.

I think I'm doing something wrong in this process of starting the server and deploying but I haven't found any information on this procedure on the web

When I start the server using "RAILS_ENV=staging rails s puma" from /current I don't get a puma process, but I see the server terminal running and I the website is working. But when I do "cap staging puma:start" from the development terminal I do see a puma process but no server terminal and I the site is not working. I copied the logs on the bottom.

these are my configuration files:

config/deploy.rb

lock '3.4.0'    set :application, "xxxxxxxxx"  set :repo_url,  "xxxxxxxxxx"  set :rbenv_ruby, '2.2.3'        set :scm, :git    set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml')      set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'tmp/save_and_open_page')      set :keep_releases, 5      set :rbenv_type, :user # or :system, depends on your rbenv setup      set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"  set :rbenv_roles, :all # default value      set :db_local_clean, true    set :db_remote_clean, true    set :disallow_pushing, true      set :maintenance_template_path, 'app/views/maintenance.html.erb'  set :maintenance_config_warning, false    set :puma_init_active_record, true    set :puma_preload_app, true      namespace :deploy do      desc "Setup maintenance reason and deadline"    task :setup_maintenance_for_deploy do        ENV['REASON'] ||= "Deployment of new version"      ENV['UNTIL'] ||= 10.minutes.from_now.to_datetime.to_formatted_s(:rfc822)    end      desc 'Runs rake db:seed'    task :seed => [:set_rails_env] do      on primary fetch(:migration_role) do        within release_path do          with rails_env: fetch(:rails_env) do            execute :rake, "db:seed"          end        end      end    end      end    namespace :tolk do      desc 'Runs rake tolk:import then rake tolk:import'    task :sync => ['deploy:set_rails_env'] do      on primary fetch(:migration_role) do        within release_path do          with rails_env: fetch(:rails_env) do            execute :rake, "tolk:sync"          end        end      end    end        desc 'Runs rake tolk:dump_all then download the locale files'    task :dump_and_download => ['deploy:set_rails_env'] do      on primary fetch(:migration_role) do        within release_path do          with rails_env: fetch(:rails_env) do            execute :rake, "tolk:dump_all"            download!("#{release_path}/config/locales/", "./config/", recursive: true)          end        end      end    end      end            before "deploy:starting", "deploy:setup_maintenance_for_deploy"  before "deploy:starting", "maintenance:enable"  after 'deploy:migrate', 'deploy:seed'  after 'deploy:publishing', 'deploy:restart'  after "deploy:finished", "maintenance:disable"  

config/environments/staging.rb

Rails.application.configure do      config.cache_classes = true        config.eager_load = true        config.consider_all_requests_local       = false    config.action_controller.perform_caching = true      config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?      config.assets.js_compressor = :uglifier        config.assets.compile = true        config.assets.digest = true      config.log_level = :debug      config.i18n.fallbacks = true      config.active_support.deprecation = :notify      config.log_formatter = ::Logger::Formatter.new      config.active_record.dump_schema_after_migration = false      config.app_domain = 'xxxxxxxxxxxxxxxx'        end  

config/deploy/staging.rb

require 'net/ssh/proxy/command'      #application information  set :branch,    "master"  set :deploy_to, "xxxxxxxx"  set :rails_env, "staging"      role :app, %w{xxxxx}  role :web, %w{xxxxxxxxxx}  role :db,  %w{xxxxxxxxxxx}, primary: true    server 'xxxxxxxxxx',         ssh_options: {             port: 22,             user: 'xxxx',         }      after 'deploy:migrate', 'tolk:sync'  

/etc/nginx/sites-available/default:

upstream xxxxxxxxxx {      server unix:/home/xxxxxxx/shared/tmp/sockets/puma.sock fail_timeout=0;  }    server {    listen 80;      server_name xxxxxxxxx5;      root /home/xxxxxxxx/current/public;      error_log /home/xxxxxxxxx/current/log/nginx.error.log;    access_log /home/xxxxxxxxxxxx/current/log/nginx.access.log;      client_max_body_size 4G;   keepalive_timeout 10;      try_files $uri/index.html $uri.html $uri @app;      location @app {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;    proxy_read_timeout 300s;        proxy_pass http://xxxxxxxxx;    }      error_page 500 502 504 /500.html;      if (-f $document_root/system/maintenance.html) {     return 503;    }      error_page 503 @maintenance;    location @maintenance {      if (-f $request_filename) {        break;      }      rewrite  ^(.*)$  /system/maintenance.html last;      break;    }  }      server {    listen 80;   listen 443 ssl;      server_name xxxxxxxxx;      ssl_certificate /etc/ssl/www-certs/xxxxxxxxx.crt;    ssl_certificate_key /etc/ssl/www-certs/xxxxxxxxxx.key;      return 301 https://www.xxxxxxxxxx;  }      server {    listen 80;      server_name www.xxxxxxxx;    return 301 https://www.xxxxxxxxxxxxxxm;  }    server {    listen 443 default_server ssl;      server_name www.xxxxxxxxxxxx;      ssl_certificate /etc/ssl/www-certs/xxxxxxxxxm.crt;    ssl_certificate_key /etc/ssl/www-certs/xxxxxxxxxxxxxx.key;        root /home/ubuntu/xxxxxxxxxxxxxxxxxxn/current/public;      error_log /home/ubuntu/xxxxxxxxxxxx/current/log/nginx.error.log;    access_log /home/ubuntu/xxxxxxxxxxxx/current/log/nginx.access.log;    client_max_body_size 4G;    keepalive_timeout 10;      try_files $uri/index.html $uri.html $uri @app;      location @app {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    proxy_set_header Host $http_host;      proxy_set_header    X-Forwarded-Proto https; # New header for SSL      proxy_redirect off;      proxy_read_timeout 300s;        proxy_pass http://xxxxxxxxxxxxxx;    }      error_page 500 502 504 /500.html;      if (-f $document_root/system/maintenance.html) {      return 503;    }      error_page 503 @maintenance;    location @maintenance {                                                                 [ line 88/13   if (-f $request_filename) {        break;      }      rewrite  ^(.*)$  /system/maintenance.html last;      break;    }  }    server {    listen 80;    listen 443 ssl;      server_name xxxxxxxxxxxx;      ssl_certificate /etc/ssl/www-certs/xxxxxxxxx.crt;   ssl_certificate_key /etc/ssl/www-certs/xxxxxxxxxxxxxx.key;      return 301 https://www.xxxxxxxxxxxxxxxxm/$request_uri?locale=fr;  }      server {    listen 80;   listen 443 ssl;      server_name www.xxxxxxxxxxxxxxxxxxxxxxr;      ssl_certificate /etc/ssl/www-certs/xxxxxxxxxxxxxxr.crt;    ssl_certificate_key /etc/ssl/www-certs/savxxxxxxxxxxxxxxr.key;      return 301 https://www.sxxxxxxxxxxf  /$request_uri?locale=fr;  }  

procfile:

redis: redis-server /usr/local/etc/redis.conf  sidekiq: bin/sidekiq  scheduler: rake scheduler  

output:

cap staging puma:restart  Using airbrussh format.  Verbose output is being written to log/capistrano.log.  max@---'s password:   00:00 puma:restart        01 RBENV_ROOT=~/.rbenv RBENV_VERSION=2.2.3 ~/.rbenv/bin/rbenv exec bundle exec pumactl -S /home/max/---/shared/tmp/pids/puma.state restart      ✔ 01 @--- 0.558s  

capistrano.log:

exec pumactl -S /home/max/save_a_train/shared/tmp/pids/puma.state restart[0m on [0;34;49m---[0m  [0;30;49mDEBUG[0m [[0;32;49md5ee0599[0m] Command: [0;34;49mcd /home/max/save_a_train/current && ( RBENV_ROOT=~/.rbenv RBENV_VERSION=2.2.3 RACK_ENV=staging RBENV_ROOT=~/.rbenv RBENV_VERSION=2.2.3 ~/.rbenv/bin/rbenv exec bundle exec pumactl -S /home/max/save_a_train/shared/tmp/pids/puma.state restart )[0m  [0;30;49mDEBUG[0m [[0;32;49m89a7b51d[0m] [0;32;49m  Command restart sent success  [0m[0;34;49mINFO[0m [[0;32;49mdac03d34[0m] Finished in 0.558 seconds with exit status 0 ([1;32;49msuccessful[0m).  

How to access google sheet api using Roo gem?

Posted: 13 Jun 2016 04:12 AM PDT

I have set up OAuth 2.0 from google developer console(as there were three type of credentials, suggest if any issue) and enabled Sheet API,

On trying below snippet from Rails console,

Roo::Google.new(sheet_key, access_token: token).first_row

throwing below error,

Attempting refresh of access token & retry of request Google::APIClient::AuthorizationError: Invalid Credentials

I am passing Client secret copied from dev-console

I have taken a reference from row-google gem initialize method

how can i fix this error?

PS: Do I have to be owner of the sheet or edit access will suffice, by the way I am accessing my owned Sheet. :)

Thanks!

Rails - auto form submit on Devise login, undefined method `permit'

Posted: 13 Jun 2016 04:51 AM PDT

I am experimenting with a Rails app - I am using Devise for user login, and I am trying to set it up so that every time a user successfully logs in, a specific entry is automatically inserted into a model called reports.

In my Devise session controller, I have the following actions related to a successful user login:

def create      self.resource = warden.authenticate!(auth_options)      sign_in(resource_name, resource)      yield resource if block_given?      respond_with resource, location: after_sign_in_path_for(resource)  end    def after_sign_in_path_for(resource)       Report.create(report_params({"comment" => "user logged in"}))   end    private      def report_params(params)          params.permit(:comment)      end  

So, if that's not clear, what I mean to do is create a new entry in reports every time a user logs in, and that entry will always read "user logged in".

However, when I try to run this, I get the following error:

undefined method `permit' for {"comment"=>"user logged in"}:Hash  

I realize that this exact operation may seem a bit pointless or redundant - as I said, I'm just experimenting, but getting this right may help me to restructure a different app that I was working on (thinking about JSONs in place of this fixed entry).

If someone could explain the meaning of this error and help me figure out what I am doing wrong (or if this is the best way to accomplish such a task), that would be much appreciated.

Model not saving Paperclip avatar data

Posted: 13 Jun 2016 04:56 AM PDT

I have a Rails 4 app that scrapes a given web page and saves the data in a Link model.

I'm using the Paperclip gem in conjunction with the after_save callback to get the url of the image and then upload it to AWS S3. This all works fine and I can view the image in my S3 bucket.

The problem I have is that the avatar_file_name, avatar_content_type, avatar_file_size and avatar_updated_at columns in the db remain nil as if there is no :avatar attached the the Link

link.rb:

class Link < ActiveRecord::Base      after_save :picture_from_url      has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/    ...        def picture_from_url        self.avatar = URI.parse(self.image_url)      end    end  

UPDATE: with Controller code

class LinksController < ApplicationController    ...      def new      @link = Link.new    end      def create      @link = Link.create(link_params)      if @link.save          flash[:success] = "Thanks for your submission!"          redirect_to link_path(@link)      else          render :new      end    end      private    def link_params      params.require(:link).permit(:title, :url, :content, :tag_list, :category, :image_url, :avatar).merge(user_id: current_user.id, author_first_name: current_user.first_name)    end    end  

No comments:

Post a Comment