Wednesday, April 6, 2016

Add attachment to email using action Mailer - Rails 4 | Fixed issues

Add attachment to email using action Mailer - Rails 4 | Fixed issues


Add attachment to email using action Mailer - Rails 4

Posted: 06 Apr 2016 06:58 AM PDT

I have book model which has title, page_no and description. There is another model Image.

class Book < ActiveRecord::Base      has_many :images, dependent: :destroy  end     class Image < ActiveRecord::Base    belongs_to :book  end  

I have used paperclips to upload the images.I need to create a button in book's show page which should send all the book's attributes along with images in email.For this I have configured the action mailer as:

rails g mailer BookMailer  

and created app/views/book_mailer/booklist_email.html.erb

<!DOCTYPE html>  <html>    <head>      <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />    </head>    <body>      <h1>Welcome to Student Library</h1>      <p>        Book: <%= @book.title %>      </p>      <p>        Page Number: <%= @book.page_number %>      </p>      <p>        Description <%= @book.description %>      </p>      <p>        Active <%= @book.active %>      </p>      <p>        Please visit us again !!      </p>    </body>  </html>  

Also I placed button in book's show page as

<%= content_tag(:button, "Send Email", :type=>:submit)%>  

Now how should I trigger the email after clicking button from book show pages which should send email to any user where email should be given at the time of pressing send email button from book show page. Let me know if I need to provide more information. I am confused how should I proceed. Please help

Staging and production environment on heroku

Posted: 06 Apr 2016 06:55 AM PDT

I want to create staging environment on heroku of an existing app. I want to know two things

1) Is it using same database of production or not? If yes then either it requires some settings or not?

2) Is the url's of both staging and production environments change or not?

Please don't give links

How to access the Mailchimp file-manager/files API endpoint using Gibbon

Posted: 06 Apr 2016 06:58 AM PDT

I'm using Gibbon to access the Mailchimp API.

I've no problem using...

gibbon = Gibbon::Request.new(api_key: "valid-api-key")  lists = gibbon.lists.retrieve  

And getting back the lists stored in the account.

However I'm struggling with the file-manager/files API endpoint.

Trying...

files = gibbon.file-manager.files  

throws a undefined local variable or method 'manager' for main:Object (NameError) error. Which suggests that the - sign is not being correctly parsed.

And...

files = gibbon.filemanager.files  

returns a 404 error as you'd expect.

So my question : Is this a problem with the Gibbon Gem or is there another way to access the file-manager/files endpoint?

Conditional validators - client_side_validations

Posted: 06 Apr 2016 06:49 AM PDT

I'm using the gem 'client_side_validations' for my Rails project and am having trouble getting a conditional validation to display on my form.

Basically, if someone selects the US from a countries dropdown, it should validate the presence of a US State.

Here is some relevant code

model - profile.rb

validates :state,            presence: { message: "State can't be blank" },            if: american?    def american?    country == 'US'  end  

view - haml file

= profile_fields.select :state, options_for_select(STATES, profile_fields.object.state), { include_blank: true }, { class: 'form-control }  

According to the Gem documentation (https://github.com/DavyJonesLocker/client_side_validations), conditional validators are turned off by default, but you can force this behavior in the form.

example

<%= f.text_field :name, validate: true %>  

I've tried this in my form, but no such luck. Can anyone help me out? If this is out of the scope for this gem, we may just have to roll our own, which will be fine. Just wanted to check on the possibility of this.

Ruby in Rails www subdomain redirect

Posted: 06 Apr 2016 06:53 AM PDT

Here is my Ruby on Rails code to redirect a request from https://example.com to https://www.example.com:

class ApplicationController < ActionController::Base  before_filter :add_www_subdomain    private        def add_www_subdomain        if Rails.env.production?          unless /^www/.match(request.host)            redirect_to("#{request.protocol}www.#{request.host_with_port}",status: 301)          end        end      end  end  

Now the issue is, when someone lands at https://example.com/product/abc they are being redirected to https://www.example.com supposedly, they should go to https://www.example.com/product/abc. Is there any trick for this? Thanks

Bundler Incompatible

Posted: 06 Apr 2016 06:46 AM PDT

I have installed latest version for ruby and rails but test install is giving error . Please could you help me resolve this issue im using windows 10

Fetching gem metadata from https://rubygems.org/....... Fetching gem metadata from https://rubygems.org/.. Resolving dependencies... Bundler could not find compatible versions for gem "activesupport": In snapshot (Gemfile.lock): activesupport (=4.2.5.1)

Running bundle update will rebuild your snapshot from scratch, using only the gems in your Gemfile, which may resolve the conflict.

Devise custom mailer using Sendgrid

Posted: 06 Apr 2016 06:27 AM PDT

I'd like to use a Sendgrid template to send users their welcome email when they signup for my site. I've checked out: Devise's How-to Use customer mailer and already done the first few steps, however, I'm stuck on where to put the confirmation_instructions method since I need to be able to put in some custom information and substitution variables to pass through. I'm also using the devise generated controller controllers/users/...

This is what I have so far:

Custom Class: models/devise_mailer.rb

class DeviseMailer < Devise::Mailer    helper :application    include Devise::Controllers::UrlHelpers    default template_path: 'devise/mailer'  end  

config/initializers/devise.rb

added: config.mailer = "DeviseMailer"

Now from here, I'm supposed to do something like below, but I don't know where to put that. Do I need to make a custom controller? If so, how do I make sure new user registrations use the method?:

def confirmation_instructions(record, token, opts={})    headers["Custom-header"] = "Bar"    super  end  

Am I way off here?

How do I avoid 401 (Unauthorized) when creating a new API endpoint for Solidus / Spree?

Posted: 06 Apr 2016 06:38 AM PDT

I'm doing a PUT "/api/shipments/H10372375236/ready_for_pickup", but that stops in Spree::BaseController#authenticate_user. My PUT request does not contain any X-Spree-Token header as required by BaseController#api_key

This is the code for my button:

 <%= form_tag(spree.api_ready_for_pickup_path(shipment), { method: "PUT", remote: true, id: "admin-ship-shipment" }) do %>     <%= submit_tag Spree.t(:ready_for_pickup), class: "ship-shipment-button" %>   <% end %>  

This is my routes:

Spree::Core::Engine.routes.draw do    namespace :api, defaults: { format: 'json' } do      put '/shipments/:id/ready_for_pickup' => 'shipments#ready_for_pickup', as: :ready_for_pickup    end  end    Rails.application.routes.draw do        mount Spree::Core::Engine, :at => '/'   end  

rake routes available as a Gist here. I have created an API key for the current user in the admin interface. How do I make sure the PUT request contain the missing X-Spree-Token?

Docker compose up fails with `require': cannot load such file -- rack/handler/rails (LoadError)

Posted: 06 Apr 2016 06:41 AM PDT

This is my Dockerfile:

FROM rails:4.2.4  MAINTAINER Brena Monteiro <me@monteirobrena.com>  RUN mkdir -p ~/myapp  COPY . ~/myapp  COPY Gemfile ~/myapp/Gemfile  COPY Gemfile ~/myapp/Gemfile.lock  WORKDIR ~/myapp  RUN bundle install  CMD rails s -b 0.0.0.0  

And my docker-compose.yml:

web:    build: .    command: rails s -p 3000 -b '0.0.0.0'    ports:      - '3000:8080'    volumes:      - .:/Users/monteirobrena/myapp  

If I run docker run the Docker is start correctly:

docker run -v ./:/Users/monteirobrena/docker/myapp -p 3000:8080 myapp  

But when I run docker-compose up I receive this error:

➜  app git:(add-docker) ✗ docker-compose up           myRecreating app_web_1  myAttaching to app_web_1  web_1 | /usr/local/bundle/gems/rack-1.6.4/lib/rack/handler.rb:78:in `require': cannot load such file -- rack/handler/rails (LoadError)  web_1 |   from /usr/local/bundle/gems/rack-1.6.4/lib/rack/handler.rb:78:in `try_require'  web_1 |   from /usr/local/bundle/gems/rack-1.6.4/lib/rack/handler.rb:16:in `get'  web_1 |   from /usr/local/bundle/gems/rack-1.6.4/lib/rack/server.rb:290:in `server'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/server.rb:125:in `print_boot_information'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/server.rb:75:in `start'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:80:in `block in server'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `tap'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `server'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'  web_1 |   from /usr/local/bundle/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'  web_1 |   from /usr/src/app/bin/rails:9:in `require'  web_1 |   from /usr/src/app/bin/rails:9:in `<top (required)>'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `load'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `call'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/client/command.rb:7:in `call'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/client.rb:28:in `run'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/bin/spring:49:in `<top (required)>'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `load'  web_1 |   from /usr/local/bundle/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `<top (required)>'  web_1 |   from /usr/src/app/bin/spring:13:in `require'  web_1 |   from /usr/src/app/bin/spring:13:in `<top (required)>'  web_1 |   from bin/rails:3:in `load'  web_1 |   from bin/rails:3:in `<main>'  web_1 | Exiting  myapp_web_1 exited with code  

Any ideas?

How create recently message like twitter [on hold]

Posted: 06 Apr 2016 05:20 AM PDT

i have table message. i need to display recently message like twitter! i use this code but don't working :

Message.where('user_id = ? OR user_two_id = ?',@hyperuser.id,@hyperuser.id)  

this returned multi record!

rails : how to add dynamic radio_buttons

Posted: 06 Apr 2016 06:13 AM PDT

I have two radio buttons.

In the first radio buttons, i have two choices:

- Men

- Women

In the second radio buttons, i have product items.

if men selected: i want to show items with "M" code,

if women selected: i want to show items with "W" code.

Here is my actual code:

.col-md-offset-2.col-md-6    = simple_form_for(@product, :html => { :role => 'form'}) do |f|      = f.error_notification      .form-inputs        = f.label :name        = f.text_field :name, :autofocus => true, class: 'form-control'          hr        = f.label :gender_id, "Gender"        br        = f.collection_radio_buttons :gender_id, Gender.all, :id, :title do |b|          .checkbox-margin            label              = b.radio_button              = b.label        hr        = f.label :category_id, "Category"        br        = f.collection_radio_buttons :category_id, Category.all, :id, :title do |b|          .checkbox-margin            label              = b.radio_button              = b.label        .form-actions        = f.button :submit  

Swagger `Unable to autoload constant`

Posted: 06 Apr 2016 06:02 AM PDT

Swagger docs are failing to build, with the error:

LoadError: Unable to autoload constant ThingsController, expected /path/to/my/app/controllers/things_controller.rb to define it  

The weird thing is, the class is defined there, and the app is working: only swagger fails.

things_controller.rb contains

class ThingsController < ActionController::Base    swagger_controller :things, "Things"      swagger_api :index do      summary "Returns list of things"    end  end  

Any ideas why Swagger would be unable to find a functioning class in the file where it is defined?

rails: login singup(registration) and admin forms

Posted: 06 Apr 2016 04:57 AM PDT

I am new to ruby on rails? I want a rails application it contain login form, registration form, order page and admin form.. user order a product it update on admin page. example: user have 3 products 1.laptop 2. phone 3.speakers, if user ordered phone, it must display on admin page like x user order phone. please help me, I am beginner, please help me

Rails 4 - Use Script Variable as Button Value

Posted: 06 Apr 2016 05:11 AM PDT

I am using a jquery ui slider (http://jqueryui.com/slider/) inside my ruby erb code.

$( "#slider" ).slider({          range:'min',          value:<%= @last_change %>,          min: 0.01,          max: 98,          step: 0.01,          slide: function( event, ui ) {              $( "#slider-value" ).html( ui.value );          }  });      $( "#slider-value" ).html(  $('#slider').slider('value') );  

The challenge is put a button using this value updated, with this script variable #slider-value. At the moment I can show this variable to on my erb (outside JS) with the following:

<p>Spinner has a value of <span id="slider-value"></span></p>

However my question is, how could I use this value on the following button:

<%= link_to "My Button", {:controller => "my_controller", :action => "my_action", :value => **slider_value_from_js** }%>

I read and I understand that js is client side and server can't handle client things => many references to use complex ajax, partials and stuff, however I don't think that's the problem here since form requests / buttons always use client inputs and that's just that what I need.

Exclude part of a string when testing in rails

Posted: 06 Apr 2016 04:47 AM PDT

How would I take a test statement that tests for two equal strings, such as, if @current_lesson.code == @current_course.answer, and exclude some parts of the answer. So, if I want to make the user write a <p> tag with anything in it, how would I make it correct, as long as they have the <p> tag?

How to make rails root change daily?

Posted: 06 Apr 2016 04:53 AM PDT

I am building a scheduling platform for a client. One requirement is that the root be the show page for today's schedule. The schedules for other days all need their own show pages, too.

I know how to write a query that will find today's schedule, but I'm having a hard time figuring out how to connect that with my routes file.

Here's what I have so far--right now I'm trying to just get it to render the show page with today's schedule. I could build a custom view for this, but I'm trying to not repeat myself, and it really would be exactly the same view as a regular show.

In the schedules controller:

def show      @schedule = Schedule.find(params[:id]) #this is actually done in a :set_schedule before_action callback, but I'm show it it here for clarity.    end      def today      @schedule = Schedule.find_by_date("#{Time.now.year}-#{Time.now.month}-#{Time.now.day}")      if @schedule         render 'schedules/show' #How do I tell it to render the show page for @schedule here??      else        render 'welcome#index'      end    end  

When I try to hit myapp.com/schedules/today that throws an error (there is no schedule with id = today).

I imagine that once I get this working, I can just do this in my routes.rb:

root 'schedules#today'  

I want to know--is this the right approach? If so, can you offer some help on my custom controller action? If not, how would you do it?

Application with dynamically/custom fields

Posted: 06 Apr 2016 04:35 AM PDT

I'm having trouble with a project, here's the deal:

An application where Users can login and store Contacts, with name and email. Also, the User must have the option to store CustomFields for its Contacts (text area, combobox), allowing them to have CustomData, e.g. fields called Street and City.

Here's how I'm thinking it should be done and what I already did, if you know what I should do now or have any advice on how to do in another way, I would appreciate.

https://gist.github.com/jonatasbaldin/906673980f847b30ec2cf6951dcb136e

Thanks.

Rails / Creating a Blog: Validation for comments (belong to a post) does not work

Posted: 06 Apr 2016 06:54 AM PDT

I'm trying to build a simple blog, where a post has many comments and the comments are displayed on the posts#show page.

I have two bugs which I cannot figure out:

  1. Validations for my comments are not working. The name and the content of a comment should be present. Whenever I try to submit an "empty" comment I got an error message: "NoMethodError in CommentsController#create: undefined method `empty?' for nil:NilClass". I suspect that in my comments_controller.rb I have to render a different page in my create action (see below for code)?
  2. Whenever I create a new post, there is always an empty "delete" link belonging to an empty comment (which no one has created. It was created automatically?). This "delete" link links to http://localhost:3000/posts/[post_id]/comments (note that after "/comments" there is no comment_id like "/comment/3/" e.g.)

routes.rb:

resources :posts do    resources :comments  end  

app/models/post.rb

class Post < ActiveRecord::Base    has_many :comments, dependent: :destroy  end  

app/models/comment.rb

class Comment < ActiveRecord::Base    validates :name, presence: true    validates :content, presence: true      belongs_to :post  end  

app/controllers/comments_controller.rb

class CommentsController < ApplicationController    before_action :set_post      def create      @comment = @post.comments.build(comment_params)        if @comment.save        flash[:success] = "Comment saved!"        redirect_to post_path(@post)      else        flash[:alert] = "Something went wrong!"        render root_path                        # I suspect here is an error?      end    end      def destroy      @comment = @post.comments.find(params[:id])      @comment.destroy        flash[:success] = "Comment deleted"      redirect_to post_path(@post)    end      private        def comment_params         params.require(:comment).permit(:name, :email, :content)      end        def set_post        @post = Post.find(params[:post_id])      end  end  

app/views/posts/show.html.erb

Here is the problem that a "Delete" link shows up whenever I create a new post. This "Delete" link belongs to a comment which is empty and strangely created automatically?

<% unless @post.comments.empty? %>          # I suspect here is an error?    <% @post.comments.each do |comment| %>      <p><%= comment.name %></p>      <p><%= comment.content %></p>      <p><%= link_to "Delete",   [comment.post, comment],                                   method: :delete,                                   data: { confirm: "Are you sure?" } %></p>    <% end %>  <% end %>  

app/views/posts/new.html.erb

<%= form_for(@post) do |f| %>    <% if @post.errors.any? %>      <div id="error_explanation">        <h2><%= @post.errors.count %> Fehler:</h2>          <ul>        <% @post.errors.full_messages.each do |msg| %>          <li><%= msg %></li>        <% end %>        </ul>      </div>    <% end %>      <div class="image-box">      <p><%= f.file_field :image%></p>    </div>      <div class="title-box">        <p><%= f.label :title, "Titel" %></p>        <p><%= f.text_field :title, class: "title-field"%></p>      </div>       <div class="content-box">        <p><%= f.label :content, "Inhalt" %></p>        <p><%= f.text_area :content, class: "content-field"%></p>      </div>      <p><%= f.submit %></p>  <% end %>  

How to validate overlapping times in Rails

Posted: 06 Apr 2016 06:07 AM PDT

I have an Event model that has form time and to time in my schedule app and I want to validate the overlapping time before saving.

My view image as followings;

Departure date: Dec 31, 2016    Day1  07:00 - 07:20 event1  10:30 - 11:30 event2  15:40 - 16:10 event3  [add event button]    Day2  08:15 - 09:05 event4  12:08 - 13:04 event5  14:00 - 14:25 event6  [add event button]    [save schedule button]  

from time and to time can be changed and added at the same time.

What I'd like to do is to display error if I try to add (or change to) 07:05 - 07:30 for Day1, for example, 13:50 - 14:30 for Day2 and so on.

Although I tried some codes with overlap, between, cover with referring to this post or this post and so on, I haven't be able to apply them to my code.

schema.rb

  create_table "events", force: :cascade do |t|      t.time     "from"      t.time     "to"      t.integer  "room_id"      ...      create_table "rooms", force: :cascade do |t|      t.integer  "schedule_id"      ...      create_table "schedules", force: :cascade do |t|      t.integer  "user_id"      t.date     "departure_date"      ...  

Give the following models:

class Schedule < ActiveRecord::Base    belongs_to :user    has_many :rooms, inverse_of: :schedule    accepts_nested_attributes_for :rooms, allow_destroy: true    ...    class Room < ActiveRecord::Base    belongs_to :schedule, inverse_of: :rooms    has_many :events, inverse_of: :room    accepts_nested_attributes_for :events, allow_destroy: true    ...    class Event < ActiveRecord::Base    belongs_to :room, inverse_of: :events    has_one :schedule, autosave: false, through: :room    ...  

_schedule_form.html.erb

  <%= render 'shared/error_messages', object: f.object %>    <%= f.label :title %>    <%= f.text_field :title, class: 'form-control' %>    <br>      <%= f.label :departure_date %>      <div class="input-group date" id="datetimepicker">        <%= f.text_field :departure_date, :value => (f.object.departure_date.strftime('%b/%d/%Y') if f.object.departure_date), class: 'form-control' %>        <span class="input-group-addon">          <span class="glyphicon glyphicon-calendar"></span>        </span>      </div>    <script type="text/javascript">      $(function () {        $('#datetimepicker').datetimepicker({format:'MMM-DD-YYYY'});      });    </script>    <br>    <div id="room">      <%= f.simple_fields_for :rooms do |a| %>        <div id="room_<%= a.object.object_id %>">          <p class="day-number-element-selector"><b>Day&nbsp;<%= a.index.to_i + 1 %></b></p>            <%= a.simple_fields_for :events do |e| %>            <span class="form-inline">              <p>                <%= e.input :from, label: false %>&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;                <%= e.input :to, label: false %>              </p>            </span>            <%= e.input :title, label: false %>          <% end %>        </div>          <%= a.link_to_add "Add event", :events, data: {target: "#room_#{a.object.object_id}"}, class: "btn btn-primary" %>          <%= a.input :room %>        <% end %>    </div>  

It would be appreciated if you could give me how to check and display error.

EDIT!

event.rb

class Event < ActiveRecord::Base    before_save :assign_date    belongs_to :room, inverse_of: :events    has_one :schedule, autosave: false, through: :room    validate :cannot_overlap_another_event    scope :in_range, -> range {    where('(start BETWEEN ? AND ?)', range.from, range.to)  }  scope :exclude_self, -> id { where.not(id: id) }    def cannot_overlap_another_event    range = Range.new from, to    overlaps = Event.exclude_self(id).in_range(range)    overlap_error unless overlaps.empty?  end    def overlap_error    errors.add(:overlap_error, 'There is already an event scheduled in this hour!')  end  

Rails model test: ERROR: null value in column [..] violates not-null constraint

Posted: 06 Apr 2016 05:11 AM PDT

I'm building a Rails 4 (4.2.6) application and right now I want to specify some Minitest-tests for a 'place' model representing Points of interests getting printed on a Leaflet-Map. As DB we're using Postgres via 'pg' gem (which shall not be relevant for the test anyhow). Unfortunately even a simple test like the following results in an error when executing bundle exec rake test:models

class PlaceTest < ActiveSupport::TestCase  def setup      @place = Place.new(latitude: 12, longitude: 52, name: 'foo', categories: 'bar')  end    test 'valid place is valid' do      assert @place.valid?  end  

The error is the following

PlaceTest#test_valid_place_is_valid:  ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "latitude" violates not-null constraint  DETAIL:  Failing row contains (980190962, null, null, 2016-04-06 11:16:08, 2016-04-06 11:16:08, null, null).  : INSERT INTO "places" ("created_at", "updated_at", "id") VALUES ('2016-04-06 11:16:08', '2016-04-06 11:16:08', 980190962)  

I have no clue how to interpret the error, since latitude is not null at all. Obviously it can't be a database related error since the instance is not being written into the db. Nevertheless the error message somehow has this sound. The schema.rb file looks like this:

ActiveRecord::Schema.define(version: 20160403170121) do    enable_extension "plpgsql"    create_table "descriptions", force: :cascade do |t|    t.integer  "place_id"    t.string   "language"    t.text     "text"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    add_index "descriptions", ["place_id"], name: "index_descriptions_on_place_id", using: :btree    create_table "places", force: :cascade do |t|    t.float    "latitude",   null: false    t.float    "longitude",  null: false    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.string   "name",       null: false    t.string   "categories", null: false  end      add_foreign_key "descriptions", "places"  end  

By the way: I can perfectly instantiate a place object within the rails console and check if .valid?. I'd be glad if someone could help me interpret that error message, thanks in advance

Edit: I have not implemented any validations in my model file (actually sth I want to persue test-driven, only the tests don't work properly...)

Rails refactor walking user through several forms

Posted: 06 Apr 2016 04:32 AM PDT

I have a feature to walkthrough users filling in several forms.

I have a controller called walkthrough with one action :build that accepts one param :step, then based on the step

  • checks whether there is a record (to create new or edit)
  • renders the appropriate form(the forms are submitted via ajax to their appropriate controllers)
  • based on the record render appropriate buttons (prev, next, skip)
  • shows a summary at the end

The issue is my controller is getting very fat.

Is there a better way to walkthrough a new user through several forms.

Note: this is not a wizard that breaks one form into several.

Data not deleted from the sqlite3 table

Posted: 06 Apr 2016 04:27 AM PDT

I am new in ruby. I want to delete record. But unable to delete. Please check my code -

ruby_win_sources/index.html.erb

<table border="1" cellpadding="1" cellspacing="1" width="100%">    <thead>      <tr>        <th>Name</th>        <th>Author</th>        <th>Url</th>        <th colspan="3">Action</th>      </tr>    </thead>      <tbody>      <% @ruby_win_sources.each do |ruby_win_source| %>        <tr>          <td><%= ruby_win_source.name %></td>          <td><%= ruby_win_source.author %></td>          <td><%= ruby_win_source.url %></td>          <td><%= link_to 'Show', ruby_win_source %></td>          <td><%= link_to 'Edit', edit_ruby_win_source_path(ruby_win_source) %></td>          <td><%= link_to 'Destroy', ruby_win_source, method: :destroy, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>    </tbody>  </table>  

ruby_win_sources_controller.rb

class RubyWinSourcesController < ApplicationController    before_action :set_ruby_win_source, only: [:show, :edit, :update, :destroy]      # GET /ruby_win_sources    # GET /ruby_win_sources.json    def index      @ruby_win_sources = RubyWinSource.all    end      # GET /ruby_win_sources/1    # GET /ruby_win_sources/1.json    def show    end      # GET /ruby_win_sources/new    def new      @ruby_win_source = RubyWinSource.new    end      # GET /ruby_win_sources/1/edit    def edit    end      # POST /ruby_win_sources    # POST /ruby_win_sources.json    def create      @ruby_win_source = RubyWinSource.new(ruby_win_source_params)        respond_to do |format|        if @ruby_win_source.save          format.html { redirect_to @ruby_win_source, notice: 'Ruby win source was successfully created.' }          format.json { render :show, status: :created, location: @ruby_win_source }        else          format.html { render :new }          format.json { render json: @ruby_win_source.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /ruby_win_sources/1    # PATCH/PUT /ruby_win_sources/1.json    def update      respond_to do |format|        if @ruby_win_source.update(ruby_win_source_params)          format.html { redirect_to @ruby_win_source, notice: 'Ruby win source was successfully updated.' }          format.json { render :show, status: :ok, location: @ruby_win_source }        else          format.html { render :edit }          format.json { render json: @ruby_win_source.errors, status: :unprocessable_entity }        end      end    end      # DELETE /ruby_win_sources/1    # DELETE /ruby_win_sources/1.json    def destroy      @ruby_win_source.destroy      respond_to do |format|        format.html { redirect_to ruby_win_sources_url, notice: 'Ruby win source was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_ruby_win_source        @ruby_win_source = RubyWinSource.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def ruby_win_source_params        params.require(:ruby_win_source).permit(:name, :author, :url)      end  end  

Delete confirm box not opening.

Please help me

Edit - routes.rb

Rails.application.routes.draw do    resources :ruby_win_sources  end  

How to set subdomain on heroku

Posted: 06 Apr 2016 03:53 AM PDT

I have an app which have multiple sub domains and work locally fine.

manager.daycare.no:3000/  worker.daycare.no:3000/  daycare.no:3000/  admin.daycare.no:3000/  parent.daycare.no:3000/  

When I deploy it on heroku these sub-domains doesn't work. Heroku app url is https://polar-harbor-19809.herokuapp.com/ .

How I set these subdomains on heroku and please tell me what will be url after subdomain urls?

copy one posgres databse to another databse with same table rails app

Posted: 06 Apr 2016 04:03 AM PDT

Currently I have multiple commerce store in my rail app using spree and database postures I want to copy all databases into single one with their foreign keys lets suppose if database A has a product with primary key 1 and database B has also a product with key 1 it should be auto incremented in tables as well as in all associated tables.

I want to some rake task.

desc "Import data bases"  task import_data: :environment do  bigbios = ActiveRecord::Base.establish_connection(    adapter: "postgresql",    encoding: "unicode",    database: "databse_a",    pool: "5",    username: "postgres",    password: "postgres"  )  Spree::Product.all  end`  

It loads product of databse A but how to load other products from second database and copy with auto incremented primary key and put this key in associated tables?

Find nearest cafe and airports of a given latitude rails

Posted: 06 Apr 2016 03:45 AM PDT

I have latitude and longitude of an address and I want to search all the airports, Railway stations, Bus Stand and cafe etc popular places. I'm using these gems in my application :

gem 'geocoder'  gem 'gmaps4rails'  gem 'geokit-rails  

Now Please suggest me how can I solve this problem?

Weird behavior of has_one after upgrade to Rails 4.2.6

Posted: 06 Apr 2016 04:52 AM PDT

I have two models:

class User < ActiveRecord::Base    belongs_to :group, dependent: :destroy      validates :login, presence: true      before_create :add_group      private      def add_group      create_group(name: login)    end  end  

and

class Group < ActiveRecord::Base    has_one :user  end  

When I try to create user, I get SystemStackError: stack level too deep. So I changed add_group callback like this:

def add_group    create_group(name: login) unless group  end  

Now, it saves the user and properly set group_id, but create also second empty record of User without validation. SQL:

>> u = User.create!(login: "foo")     (0.7ms)  BEGIN    SQL (2.2ms)  INSERT INTO "groups" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["name", "foo"], ["created_at", "2016-04-06 10:09:52.981954"], ["updated_at", "2016-04-06 10:09:52.981954"]]    Group Load (1.2ms)  SELECT  "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1  [["id", 1453]]    SQL (2.0ms)  INSERT INTO "users" ("login", "created_at", "updated_at", "group_id") VALUES ($1, $2, $3, $4) RETURNING "id"  [["login", "foo"], ["created_at", "2016-04-06 10:09:52.923926"], ["updated_at", "2016-04-06 10:09:52.923926"], ["group_id", 1453]]    SQL (1.4ms)  INSERT INTO "users" DEFAULT VALUES RETURNING "id"     (9.1ms)  COMMIT  

The last INSERT INTO users table is odd. I can't figure out why this happens...

I found two solutions:

class Group < ActiveRecord::Base    has_one :user, autosave: false    ##OR##    has_one :usr, class_name: "User"      # has_one :user, class_name: "User" works weird too  end  

but it doesn't convince me.

What can be wrong? at Rails 4.0 everything works well.

UPDATE 1

ok, I found 2 other solutions:

class User < ActiveRecord::Base    belongs_to :group, dependent: :destroy      validates :login, presence: true      before_create :add_group      private      def add_group      self.group = Group.create(name: login)      # OR #      assign_attributes(group: Group.create(name: login))    end  end    class Group < ActiveRecord::Base    has_one :user  end  

but still I don't understand why it's behave so strange... especially this extra empty record and fix by has_one :usr, class_name: "User"

Do an action after Sidekiq jobs are completed without Sidekiq pro

Posted: 06 Apr 2016 03:30 AM PDT

Here is my problem.

I have a 'Job' model which has many 'transactions'.

I have a Transaction processor worker, which takes ID of the transaction and proceeds to process all the transactions of this job.

Eg:

job.transactions.each do |transaction|     TransactionWorker.perform_async(transaction.id)  end  

My requirement is that, I should intimate the user who created this job with an email, after all the transactions are complete. The transaction model has a field called 'status' which is updated in the worker itself, when it is complete.

 transactions.status = "complete"   transaction.save  

The problem is that since Sidekiq is treaded, multiple treads are processing transactions at once. I am checking for

  job.transactions.to_be_processed.count == 0   

for sending the mail. Since it is treaded, I have been receving more than 1 mail per job.

Questions:

What should be done to make this error proof, without using sidekiq pro? I thought of moving the job completion check to after_update callback of transaction model. Will that work?

uninitialized constant ActionController::Caching::Sweeping (NameError)

Posted: 06 Apr 2016 04:18 AM PDT

its an api based application

using rails 4.1.13

gem 'rails-observers'

app/config/initializers/base_sweeper.rb

class BaseSweeper < ActionController::Caching::Sweeper    observe ActiveRecord::Base      def after_save(object)      # ..... call to version class for record saving purpose    end    end  

application.rb

config.autoload_paths += %W(#{config.root}/services #{config.root}/lib)  

app/services/version.rb

class Version    #some method to store records  end  

ChannelController.rb

classs Api::V1::ChannelsController < Api::V1::BaseController   cache sweeper :base_sweeper, only: [:create, :update]  end    #channel.rb  has_many :channel_logs    #channel_log.rb  belongs_to :channel    development.rb  config.active_record.observers = :base_sweeper  

I got an error uninitialized constant basesweeper?

activeadmin : wrong number of arguments (0 for 1) on member_action

Posted: 06 Apr 2016 04:04 AM PDT

i'm building my RoR app admin interface using active admin, got an exception i'm stuck on trying to set up custom actions :

    ActiveAdmin.register Deal do        [:cancel, :release].each do |event|          member_action event , method: :patch do |deal|            deal.send :"#{event}!"            redirect_to admin_deal_path(deal), notice: "Your event was #{deal.current_state}"          end            action_item event, only: :show do            link_to event, url_for(action: event), method: :patch          end          end      end  

The event links display well on the page but when clicking on one of them got the following exception :

ArgumentError (wrong number of arguments (0 for 1)):  app/admin/deal.rb:45:in `block (3 levels) in <top (required)>'  app/admin/deal.rb:45:in `block (3 levels) in <top (required)>'    actionpack (4.2.6) lib/action_controller/metal/implicit_render.rb:4:in `send_action'  actionpack (4.2.6) lib/abstract_controller/base.rb:198:in `process_action'  actionpack (4.2.6) lib/action_controller/metal/rendering.rb:10:in `process_action'  actionpack (4.2.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'  

activesupport (4.2.6) lib/active_support/callbacks.rb:117:in call' activesupport (4.2.6) lib/active_support/callbacks.rb:117:incall' activesupport (4.2.6) lib/active_support/callbacks.rb:555:in block (2 levels) in compile' activesupport (4.2.6) lib/active_support/callbacks.rb:505:incall' activesupport (4.2.6) lib/active_support/callbacks.rb:505:in call' activesupport (4.2.6) lib/active_support/callbacks.rb:92:inrun_callbacks' activesupport (4.2.6) lib/active_support/callbacks.rb:778:in _run_process_action_callbacks' activesupport (4.2.6) lib/active_support/callbacks.rb:81:inrun_callbacks' actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in process_action' actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:inprocess_action' actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in block in process_action' activesupport (4.2.6) lib/active_support/notifications.rb:164:inblock in instrument' activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in instrument' activesupport (4.2.6) lib/active_support/notifications.rb:164:ininstrument' actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in process_action' actionpack (4.2.6) lib/action_controller/metal/params_wrapper.rb:250:inprocess_action' activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in process_action' actionpack (4.2.6) lib/abstract_controller/base.rb:137:inprocess' actionview (4.2.6) lib/action_view/rendering.rb:30:in `process'

Line 46 of admin/deal.rb is the line where member_action is called, it seems the activeadmin method is overided somehow somewhere or there is something else obvious i don't see...

Any idea where it could come from ? amon other gems I'm using cancancan, devise, and responders.

Thanks in advance

**UPDATED : full stacktrace **

What is the Rails way to do this - shared controllers/views or separate?

Posted: 06 Apr 2016 03:05 AM PDT

I have 2 types of users in an app I have just picked up that I need to enhance.

Admins, who can do everything

RoomAdmins, who can only manage anything to do with their Room - like adding Parents, who belong to the Room.

For example, RoomAdmins when they sign up, can CRUD Parents for their room (for which there is already a RoomAdmin/ParentsController).

Now I need to give Admins the ability to manage Parents. So should I create an Admin/ParentsController and create a set of views specific to those use cases?

Or is the 'Rails' convention to move the RoomAdmin/ParentsController to app/controllers and have both RoomAdmins and Admins share that controller? This will make that controller far more complex (and the views also).

Bear in mind that the views will be slightly different for each Admin type, and the logic in each action will have minor differences depending on where we route to after each action based on whether it is an Admin or a RoomAdmin acting on that parent.

So which option is the Rails convention?

A - separate controllers, separate views

B - one controller, one set of views, more complex logic to handle the differences?

EDIT

There is added complexity I forgot here, which is the controller inheritance chain, since both types of users have a different main layout and sign-in process:

All controllers dealing with Rooms currently inherit from RoomAdminsController.

All controllers dealing with Admin functionality inherit from AdminController.

So RoomAdmin/ParentsController currently inherits from RoomAdminsController.

If I move it, which one does it then inherit from? Agh!

15 comments:

  1. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work.
    pg online

    ReplyDelete
  2. I read this article. I think You put a lot of effort to create this article. I appreciate your work.
    https://www.ufa365.info/

    ReplyDelete
  3. Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
    แทงบอลเต็ง

    ReplyDelete
  4. I must say, I thought this was a pretty interesting read when it comes to thisC topic. Liked the material. . .
    แทงบอลสเต็ป

    ReplyDelete
  5. I went over this website and I believe you have a lot of wonderful information, saved to my bookmarks
    รีวิวเว็บพนัน

    ReplyDelete
  6. I must say, I thought this was a pretty interesting read when it comes to thisC topic. Liked the material. . .
    ufa365

    ReplyDelete
  7. Consequently, starting in the amount of electronic marketing strategy, is whenever a company's existing website, which will be to review the present site and its purpose is to improve the potency of the future. There is no evidence that the development and implementation of a method to be significantly different way of electronic marketing. Strategic planning for enterprise development or strategic marketing to comply with the established framework should still be
    เว็บแทงบอลออโต้

    ReplyDelete
  8. I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job!
    UFA365

    ReplyDelete
  9. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this.
    ทำไมต้องเล่นบาคาร่า

    ReplyDelete
  10. So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site.
    แทงบาสเว็บไหนดี

    ReplyDelete
  11. Internet search engine optimization experts apply the modern analytics service, which has a positive affect a website. SEO companies are facing great competition in the SEO field. However, they introduce guaranteed SEO services to manage with the competition.

    บาคาร่าsa-gaming

    ReplyDelete
  12. his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
    แทงบาสออนไลน์

    ReplyDelete
  13. his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
    คาสิโนออนไลน์ฟรีโบนัส/

    ReplyDelete
  14. his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
    lucky-god

    ReplyDelete
  15. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! ประวัตินักกีฬา

    ReplyDelete