Saturday, June 18, 2016

no model validation call or saving on update | Fixed issues

no model validation call or saving on update | Fixed issues


no model validation call or saving on update

Posted: 18 Jun 2016 08:14 AM PDT

My WordExposition model keeps track of whether a user copies a displayed Word.term correctly. It should validate whether word_from_student_matches_word on update. Word expositions' have a :completed parameter that is set to false on enrollment, and as users copy the terms correctly the attribute should update to true. I'm using simple form to receive a user's input (:term_given_by_student), which should be checked against the model method on update, and the WordExposition :completed attribute changed to true if successful.

As of now I'm unable to get the form to either call the validation, or to save and update the instance of WordExposition. I included an alert in the update method, if the form doesn't save for testing purposes, and I only get that alert and redirection. How can I get the update action to change to true if the user input matches the term displayed? I'm fairly new to rails--any feedback on these issues be well received.

WordExposition model:

class WordExposition < ActiveRecord::Base    belongs_to :enrollment    belongs_to :word      delegate :term, to: :word     delegate :reference, to: :word    delegate :image, to: :word    delegate :sound, to: :word      attr_accessor :term_given_by_student    validate :word_from_student_matches_word, on: :update      def word_from_student_matches_word      return true if word.term == term_given_by_student      errors.add(:term_given_by_student, "Terms don't match")    end      def next_exposition      WordExposition.where(["id > ? AND enrollment_id = ?", id, enrollment_id]).first    end  end  

WordExpositions controller:

class WordExpositionsController < ApplicationController    before_action :authenticate_user!    before_action :require_enrollment_in_lesson      def show      @word = current_enrollment.word_expositions.find_by!(word_id: params[:id])    end      def update      current_word_exposition      current_word_exposition.completed = true      if current_word_exposition.save        flash[:notice] = "Congratulations!"        redirect_to current_word_exposition.next_exposition      else        flash[:alert] = "Did not save :("        redirect_to lesson_word_exposition_path(current_lesson, current_word_exposition)      end    end      private      helper_method :current_lesson    def current_lesson      @current_lesson ||= Lesson.find(params[:lesson_id])    end      helper_method :current_enrollment    def current_enrollment      @current_enrollment ||= Enrollment.find_by!(lesson_id: params[:lesson_id], user_id: current_user.id)    end      def require_enrollment_in_lesson      if !(current_user.enrolled_in?(current_lesson))        redirect_to lesson_path(current_lesson), alert: 'You need to enroll in order to view the activities!'      end    end      def word_exposition_params      params.require(:word_exposition).permit(:completed)    end      helper_method :current_word_exposition    def current_word_exposition      @current_word_exposition ||= current_enrollment.word_expositions.find_by!(word_id: params[:id])    end  end  

WordExposition show view:

<div>    <h2><%= @word.term %></h2><br>      <!-- Form to ensure that user copies the term accurately -->    <%= simple_form_for @word, url: lesson_word_exposition_path(current_lesson, @word), method: :patch do |f| %>      <%= f.input :term_given_by_student, label: "Enter the term exactly as above:" %>      <%= f.button :submit, class: 'btn btn-primary' %>    <% end %>  </div>  

HTTParty read_nonblock connection reset by peer Errno::ECONNRESET

Posted: 18 Jun 2016 07:47 AM PDT

I'm a new Ruby developer. I would like to send some concurrent requests (maximum 3 requests) at same time to get data. I know there are a lot of Http libs in Ruby that support for sending request. In the end, I choose HTTParty, however, it comes to some error when I try to send request.

response_data = Http::SearchFlightService.search(url, options)  

The url value:

http://booknow.jetstar.com/Search.aspx?culture=vi-VN  

And value of options params:

{:body=>{"search-origin01"=>"", "search-destination01"=>"", "ControlGroupSearchView$ButtonSubmit"=>"", "__VIEWSTATE"=>"", "undefined"=>"", "children"=>"0", "infants"=>"0", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_INFANT"=>"0", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_CHD"=>"0", "datedepart-01"=>"19/06/2016", "datereturn-01"=>"20/06/2016", "adults"=>"1", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDay1"=>"19", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_ADT"=>"1", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDay2"=>"20", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketMonth1"=>"2016-06", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketMonth2"=>"2016-06", "ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin1"=>"SGN", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListFareTypes"=>"I", "_pe_39b5379c652b_9df496572198"=>"null", "travel-indicator"=>"on", "ControlGroupSearchView$AvailabilitySearchInputSearchView$RadioButtonMarketStructure"=>"RoundTrip", "ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination1"=>"HAN", "pageToken"=>"sLkmnwXwAsY=", "culture"=>"vi-VN", "locale"=>"vi-VN", "currencyPicker"=>"VND", "ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListCurrency"=>"VND"}, :headers=>{"Accept-Encoding"=>"gzip, deflate", "Content-type"=>"application/x-www-form-urlencoded"}}  

My Http::SearchFlightService

class Http::SearchFlightService    include HTTParty    ssl_version :SSLv3    def self.search(url, options)      post(url, options)    end  end  

It showed error

/Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:153:in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:153:in `rbuf_fill'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:104:in `read'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:399:in `read'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:289:in `block in read_body_0'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:260:in `inflater'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:279:in `read_body_0'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:201:in `read_body'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:226:in `body'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:163:in `reading_body'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1420:in `block in transport_request'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1411:in `catch'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1411:in `transport_request'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1384:in `request'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1377:in `block in request'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:853:in `start'      from /Users/Dona/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1375:in `request'  

Please give me some advice. Thanks

Password policy using regular expression Ruby

Posted: 18 Jun 2016 07:25 AM PDT

I have created a Regular Expression

^(?=.*[a-z]{2})(?=.*[A-Z]{2})(?=.*\d{2})(?=.*([%]{2})).{8,10}$  

which help me to restrict 2 Lower Case + 2 Uppercase + 2 Digit+ special character , and tge total length should be between 8-10. Ex: aaAA12%% will be a valid string. but, I need to make aAaA%3%3 also a valid string. how to do the negative of lookahead match in ruby

Expectation: The string should contain exact number of uppercase,lowercase,digit & specific special character irrespective of their order.It can be in any order followed with UpperCase and lowwercase .

Ex: 2 uppercase,2lowercase,2digit,+special character ( aA1B%b2&)

Ruby On Rails Active Admin Create Action "Render and/or redirect were called multiple times in this action. "

Posted: 18 Jun 2016 06:57 AM PDT

I have a problem with updating one field in Active Admin Create Controller Action. My code:

params[:document].merge!({ createdby: current_user.id })  create!  redirect_to admin_documents_path, :notice => "Document added!"  

I need after update attribute createdby to save a document and to redirect to admin_documents path.

But I am getting the error:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

And if I remove last line :"redirect_to admin_documents_path, :notice => "Document added!""

Then I am redirected to create page (which is blank).

So, problem is with updating field in create action and redirection after.

Conntroller:

def create      if File.exist?(Rails.root.join('uploads','',params[:document][:link]))      redirect_to admin_documents_path, :notice => "Document with name #{params[:document][:link]} already exists. Please rename it and upload again!"    else      uploaded_io = params[:document][:content]      File.open(Rails.root.join('uploads', '', uploaded_io.original_filename), 'wb') do |file|        file.write(uploaded_io.read)      end        params[:document].merge!({ createdby: current_user.id })      create!      redirect_to admin_documents_path, :notice => "Document added!"      end  end  

In controller I am uploading new document and checking for existing on file system, updating one field and saving document on file system and document attributes into db.

link_to with nested resourses edit_path

Posted: 18 Jun 2016 07:40 AM PDT

In my routes i have:

    resources :users do        resources :orders      end  

so when i create a link wich leads to 'show' action i can simply make

<%= link_to "Details", [@order.user, @order] %>  

But what should i write if i want to make link_to for 'edit' action?

in my orders_controller:

@order = Order.find params[:id]  

so i've tryed this code:

<%= link_to "Edit", edit_user_order_path([@order.user, @order]) %>  

but somehow edit_user_order_pathmethod cant get :id parametr from @order object, error says me:

missing required keys: [:id]

while user_id is returning!

Help plz!

Avoid duplicate entires at the same time

Posted: 18 Jun 2016 06:26 AM PDT

I have a growing application and my concern is that when you purchase an order, we delegate it to a person. However as we're scaling now I'd like to find a solution where a person can be delegated two orders at the same time, if two different customers purchase at the same time.

Currently our order goes through a state machine (AASM) where it connects:

event :connect, after: :find_person do    transitions from: :pending, to: :connecting  end  

and the find_person looks like this:

  def find_person      person = Person.where(aasm_state: 'available').order('RANDOM()').first      if person        person.requested!        create_order_request(person: person)      else        person_unavailable!      end   end  

now how can I avoid that if two entries come in at the same time that they won't both be delegated to this person. If a person is found, I move their status to requested. Which means that they can't receive a new order (because I look for only people that are 'available').

Need help integrating rails form_tag with HTML themed page

Posted: 18 Jun 2016 05:15 AM PDT

I'm working with a themed HTML Template and trying to reverse engineer my Rails create an email Form into the "compose an email" template. But no matter how i structure the rails code, it breaks the html form... I think it could be because as part of the template the is already some tags in it, but their only at the top half of the form

Below is the rails form code i have. A pretty simple set of critera for an email

    <%= form_tag messages_path, method: :post do %>    <div class="form-group">      <%= label_tag 'message[subject]', 'Subject' %>      <%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>    </div>      <div class="form-group">      <%= label_tag 'message[body]', 'Message' %>      <%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>    </div>      <div class="form-group">    <%= label_tag 'recipients', 'Choose recipients' %>    <%= select_tag 'recipients', recipients_options, multiple: true, class: 'form-control chosen-it' %>  </div>      <%= submit_tag 'Send', class: 'btn btn-primary' %>  <% end %>  

And this is the template I'm trying to integrate it into

<div class="wrapper wrapper-content">  <div class="row">        <!-- start left pane nav bar -->      <div class="col-lg-3">          <div class="ibox float-e-margins">              <div class="ibox-content mailbox-content">                  <div class="file-manager">                      <a class="btn btn-block btn-primary compose-mail" href="<%= url_for :controller => 'mailbox', :action => 'compose_email' %>">Compose Mail</a>                      <div class="space-25"></div>                      <h5>Folders</h5>                      <ul class="folder-list m-b-md" style="padding: 0">                          <li><a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>"> <i class="fa fa-inbox "></i> Inbox <span class="label label-warning pull-right">16</span> </a></li>                          <li><a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>"> <i class="fa fa-envelope-o"></i> Send Mail</a></li>                          <li><a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>"> <i class="fa fa-trash-o"></i> Trash</a></li>                      </ul>                      <div class="clearfix"></div>                  </div>              </div>          </div>      </div>      <!-- end left pane nav bar -->        <!-- HTML Form Start -->      <div class="col-lg-9 animated fadeInRight"> <!-- form fades in on page load -->          <div class="mail-box-header">              <div class="pull-right tooltip-demo">                  <a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>" class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="Move to draft folder"><i class="fa fa-pencil"></i> Draft</a>                  <a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>" class="btn btn-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Discard email"><i class="fa fa-times"></i> Discard</a>              </div>              <h2>Compose mail</h2>          </div>          <div class="mail-box">              <div class="mail-body">                  <form class="form-horizontal" method="get">                      <!-- To: entry start -->                      <div class="form-group">                          <label class="col-sm-2 control-label">To:</label>                          <div class="col-sm-10"><input type="text" class="form-control" value="alex.smith@corporat.com">                          </div>                      </div>                      <!-- To: entry start -->                      <!-- Subject entry start -->                      <div class="form-group">                          <label class="col-sm-2 control-label">Subject:</label>                          <div class="col-sm-10"><input type="text" class="form-control" value="">                          </div>                      </div>                      <!-- Subject entry end -->                  </form>              </div>              <div class="mail-text h-200">                  <div class="form-group">                      Writing the contents of the email                  </div>                  <div class="clearfix"></div>              </div>              <!-- email action buttons start -->              <div class="mail-body text-right tooltip-demo">                  <a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>" class="btn btn-sm btn-primary" data-toggle="tooltip" data-placement="top" title="Send"><i class="fa fa-reply"></i> Send</a>                  <a href="<%= url_for :controller => 'mailbox', :action => 'inbox' %>" class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="Discard email"><i class="fa fa-times"></i> Discard</a>              </div>              <!-- email action buttons end -->                <div class="clearfix">              </div>          </div> <!--class="mail-box" end -->      </div> <!-- class="col-lg-9 animated fadeInRight" end the fading in form from page load -->      <!-- HTML Form end -->  </div>  

Any help would be amazing, pulling my hair out!

Rails image_submit_tag not working on Heroku

Posted: 18 Jun 2016 04:31 AM PDT

I have a Rails 4 app and I'm using image_submit_tag to use a picture in a form as the submit button.

<%= form_for @stamp do |f| %>    <div class="field">      <%= f.hidden_field :remote_image_url, value: current_user.image %>    </div><br>    <div class="form-group text-center">      <%= image_submit_tag(@user.image, class: "img-responsive center-responsive", id: "users-show-preview") %>    </div>  <% end %>  

The image displays and functions as a submit perfectly on my local machine. When I upload the app to Heroku, no image is displayed, and subsequently no image is available to click in the browser.

In Heroku console there is a valid value in the DB for @user.image. I've also compared the HTML that is output by the local and Heroku versions and it's identical.

I've tested it on Chrome, Safari and Firefox.

Please let me know if you need me to post more code.

Saving either remote image or local image in Carrierwave

Posted: 18 Jun 2016 04:26 AM PDT

I'm making an Omniauth registration form which allows user either to save his Last.fm avatar or upload a new avatar. So I want to make the following: if local file is not chosen then Omniauth avatar is saved, but if local file is chosen then local file is saved.

I tried to do this using :remote_avatar_url but it saves both of the images. Is there a way to let Carrierwave know that it should only save the last uploaded image?

starting rails application with passanger for apache

Posted: 18 Jun 2016 03:01 AM PDT

I've got a rails application actually run on passanger stand alone server.

Now I want to use the apache module. But I can't start or don't know how to start.

When I set up the vhost settings what do I have to do to start the rails app?

How do I preserve a url fragments during a redirect in Rails?

Posted: 18 Jun 2016 02:56 AM PDT

I want URLs to maintain their fragments while redirecting from the login page.

Here is an example.

This Url http://localhost:3000/my-to-dos?utm_source=My+Newsletter&utm_campaign=99ggcc1b7a-&utm_medium=email&utm_term=0_cdb53c32ed-99ggcc1b7a- returns http://localhost:3000/my-to-dos?utm_source=My%20Newsletter after login. All the other utm_campaign fragments get lost. How can I preserve these fragments? I have tried to use URI.ecode, but it still did not work.

Passing arguments to a Concern, using in association

Posted: 18 Jun 2016 05:37 AM PDT

I have a Concern to set up some much used associations (among other things), but I need to make some small tweaks depending on the class where the concern is used. My basic concern looks like this:

module Organizable    extend ActiveSupport::Concern      included do      has_many :person_organizations        has_many :organizations,               through:     :person_organizations,               class_name:  <STI CLASS NAME HERE>    end  end  ```  

As you can see I want to be able to change the class name in the organizations association.

I was thinking I could include some class methods to provide this support, but I am unable to figure our how to proceed to fetch this value. Here is how I see myself using it:

class Dentist < Person    include Organizable    organizable organization_class: DentistClinic  end  

And here is my current version of the code:

module Organizable    extend ActiveSupport::Concern      module ClassMethods      attr_reader :organization_class      private        def organizable(organization_class:)        @organization_class = organization_class      end    end      included do      has_many :person_organizations        has_many :organizations,               through:     :person_organizations,               class_name:  self.class.organization_class.name    end  end  

I think there are at least two problems with this:

1) The .organization_class method doesn't seem to be defined at the time the association is set up, as I'm getting a NoMethodError: undefined methodorganization_class' for Class:Class` when I load the Dentist model.

2) I guess the association inside the concern will be evaluated before i even get to pass the class to the concern (the organizable organization_class: DentistClinic line), so it would not contain a value anyway.

I'm really unsure about how to get around this. Is there a way to pass this parameter into the concern and have the association set up using this value?

Mongoid and AMS(JSON API) relationship performance issue

Posted: 18 Jun 2016 02:28 AM PDT

I'm using Mongoid and ActiveModelSerializers together to realize a jsonapi.org conform API. Currently I have performance problems with the index operations of some resources, because my serializer loads the related object just to get the id (no include param).

Is there a better way to serialize the relationships with mongoid and AMS?

My objects

class Parent    include Mongoid::Document    ...    has_one :big_child_document  end    class BigChildDocument    include Mongoid::Document    ...    belongs_to :parent  end    class ParentSerializer < ActiveModel::Serializer    attributes ...    has_one :big_child_document do      link :related do       ...      end    end  end  

Output

{        "id": "575d4c8439cd6b9951000000",        "type": "parent",        "attributes": {          ....        },        "relationships": {          "big_child_document": {            "data": {              "id": "575d4c8439cd6b9951000001",              "type": "big_child_document"            },            "links": {              "related": "/api/parent/575d4c8439cd6b9951000000/big_child_document"            }          }        }  }    MONGODB | localhost:27017 | test.find | STARTED | {"find"=>"parents", "filter"=>{}}  MONGODB | localhost:27017 | test.find | SUCCEEDED | 0.002491s  MONGODB | localhost:27017 | test.getMore | STARTED | {"getMore"=>24294891564, "collection"=>"parents"}  MONGODB | localhost:27017 | test.getMore | SUCCEEDED | 0.003303s  [active_model_serializers] MONGODB | localhost:27017 | test.find | STARTED | {"find"=>"big_child_documents", "filter"=>{"parent_id"=>BSON::ObjectId('575d4c8439cd6b9951000000')}, "limit"=>1, "singleBatch"=>true}  [active_model_serializers] MONGODB | localhost:27017 | test.find | SUCCEEDED | 0.002414s  ...  ...  ... for every object  

Unfortunately there are only a few articles about AMS and Mongoid and I couldn't find a best practice.

Designing models with Ruby On Rails

Posted: 18 Jun 2016 04:20 AM PDT

I have the following models:

  • Institute
  • Student
  • Classroom
  • Course

Requirements:

  1. A classroom can have many courses. A course can belong to many classrooms.
  2. A classroom can have many students. A student can belong to many classrooms.
  3. A student can take many courses. A course can belong to many students.
  4. An institute has many students, many classrooms and many courses.

I'm trying to create associations for the above: Would the following be accurate?

  1. Institute: has_and_belongs_to_many :users | has_many :classrooms | has_many :courses
  2. Student: has_and_belongs_to_many :institutes | has_and_belongs_to_many :classrooms | has_many :courses | belongs_to :institute
  3. Classroom: has_and_belongs_to_many :users | has_many :courses | belongs_to :institute
  4. Course: has_and_belongs_to_many :users | has_many :classrooms | belongs_to :institute

How do I use the "through" relationship here?

rails 4 - param is missing or the value is empty: projecttype

Posted: 18 Jun 2016 02:23 AM PDT

A newby to rails (I am building an app to learn rails) and run in to an issue I can't find a solution to (while following the getting started guide). I have studied the guides and similar questions

This is my code:

    class ProjecttypesController < ApplicationController      def index          @projecttypes = Projecttype.all      end        def show          @projecttype = Projecttype.find(params[:id])      end        def new      end        def create          @projecttype = Projecttype.new(projecttype_params)          @projecttype.save          redirect_to @projecttype      end        private          def projecttype_params              params.require(:projecttype).permit(:name, :image, :url)          end  end  

The form:

    <%= form_for :projecttypes, url: projecttypes_path do |f| %>      <p>          <%= f.label 'Project type' %>          <%= f.text_field :projecttype %>      </p>        <p>          <%= f.label :name %>          <%= f.text_field :name %>      </p>        <p>          <%= f.label :image %>          <%= f.file_field :image %>      </p>        <p>          <%= f.label :url %>          <%= f.url_field :url %>      </p>        <p>          <%= f.submit %>      </p>  <% end %>  

What am I doing wrong?

Perhaps important... when I use this...

def create      render plain: params[:projecttype].inspect  end  

It returns 'nil'.

Thanks for your help

Inserting into database via web service

Posted: 18 Jun 2016 03:11 AM PDT

I'm working on inserting users into my database via a web service, but each time I try to do so, the web service returns the following error: TinyTds::Error: There are more column in the INSERT statement than values specified in the VALUES clause. I don't see the problem as there are 5 values in each statement.

post '/insert_users/' do  conn = TinyTds::Client.new(...)  username = params[:username]  password = params[:password]  phone_number = params[:phone_number]  profile_state = params[:profile_state]  clasa = params[:clasa]  sql = "insert into ServerUsers(Username, Passwords,Phone_Number, Profile_State, Class) values('username, password, phone_number, profile_state, clasa')"  cursor = conn.execute(sql)  end  

This is how I try to insert into the database via the web service:

http://address:port/insert_users/?username=user3&password=parola3&phone_number=0723567432&profile_state=A&clasa=2

I am using Advanced REST client to test the webservice.

I used the tutorial here: https://github.com/rails-sqlserver/tiny_tds

Rails case statement and flash messages

Posted: 18 Jun 2016 02:11 AM PDT

I am trying to add flash msg Bootstrap 3 haml in rails 5 app. Only the flash-info in the else part of the case statement is displaying no matter what. What is wrong with my code

module ApplicationHelper    def twitterized_type(type)    case type.to_s        when :errors          "alert-danger"      when :alert          "alert-danger"      when :error          "alert-danger"      when :notice          "alert-success"      when :success          "alert-success"      when :warning          "alert-warning"      else          "alert-info"      end    end  

flash message in application.html.haml

.container        - flash.each do |type, message|          .alert.alert-dismissable{ :class => twitterized_type(type) }              = message              %button.close{ data: { dismiss: 'alert' } } x  

Controller:

def create  @pin = current_user.pins.build(pin_params)  if @pin.save    # Display success flash message then redirect to the saved pin    flash[:success] = 'New pin saved successfully'    redirect_to @pin  else    # Display a fail flash message and render new    flash[:alert] = 'New pin failed to save, please try again'    render 'new'  end       def update  if @pin.update_attributes(pin_params)    # save update and display success flash message    flash[:success] = 'Pin was updated successfully'    redirect_to @pin  else    # flash error message and redirect to edit    flash[:alert] = 'Pin failed to update, please try again'    render 'edit'  end  

How to make the flash displayed with the intended class

Rails - populating subcategory based on category selection

Posted: 18 Jun 2016 03:24 AM PDT

I'm trying to make a helper that provides a set of input values, for an attribute called :subcategory, based on the value of another attribute called :category.

I have a form which has:

<div class="nested-fields">  <div class="container-fluid">      <div class="form-inputs">        <%= f.input :irrelevant, :as => :boolean, :label =>  "Is an ethics review required or applicable to this project?"  %>        <%= f.input :category, collection: [ "Risk of harm", "Informed consent", "Anonymity and Confidentiality", "Deceptive practices", "Right to withdraw"], :label => "Principle",  prompt: 'select' %>        <%= f.input :subcategory,  collection: text_for_subcategory(@ethic.category), :label => "Subcategory", prompt: 'select'  %>          <%= f.input :considerations, as: :text, :label => "Identify the ethics considerations?",  :input_html => {:rows => 8} %>        <%= f.input :proposal, as: :text, :label => "How will these considerations be managed?",  :input_html => {:rows => 8} %>        </div>    </div>    </div>  

I then have a helper which has the input I want to use for :subcategory:

module EthicsHelper      def text_for_subcategory(category)        if @ethic.category == 'Risk of harm'              [ "Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]          elsif @ethic.category == 'Informed consent'              ["Explanation of research", "Explanation of participant's role in research"]          elsif @ethic.category == 'Anonymity and Confidentiality'              ["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]          elsif @ethic.category == 'Deceptive practices'                "Feasibility"             else @ethic.category == 'Right to withdraw'               "Right to withdraw from participation in the project"            end      end      end  

Can anyone see where I'm going wrong? I want the category value to determine the values of the input field for subcategory.

When I try this, I get an error that says:

undefined method `category' for nil:NilClass  

Controller I have a projects controller with the following actions:

def new      @project = Project.new      @project.ethics.build       def show        end          end      # GET /projects/1/edit    def edit       @project.ethics_build unless @project.ethics    end  

Projects has many ethics and ethics belongs to project.

What is the best combination of ruby framework and app server for static pages? [on hold]

Posted: 18 Jun 2016 04:14 AM PDT

I want to create a application which has mostly static pages and only one dynamic page. Which Ruby framework should be used considering caching and other performance factors? Sinatra Or Rails

And also which app server will be better for such application? Unicorn, Passenger, puma Or thin. I'm using nginx web server.

Nested forms, running into weird errors

Posted: 18 Jun 2016 01:43 AM PDT

I'm making a survey app, I've got 3 models: Survey, Question, and Answer. Survey has_many questions, Question has_many answers.

I've got two main errors:

  1. My code is supposed to generate 4 answer fields for each question but only 1 answer field is generated.
  2. When I press submit on my form, I get

    unknown attribute 'answers' for Survey. Extracted source (around line #33):

      # POST /surveys.json    def create      @survey = Survey.new(survey_params)        respond_to do |format|        if @survey.save  

I think the second problem is related to the answers model in some way but I'm not sure how. Here's my code:

surveys_controller:

class SurveysController < ApplicationController    before_action :set_survey, only: [:show, :edit, :update, :destroy]      # GET /surveys    # GET /surveys.json    def index      @surveys = Survey.all    end      # GET /surveys/1    # GET /surveys/1.json    def show    end      # GET /surveys/new    def new      @survey = Survey.new      3.times do        question = @survey.questions.build        4.times { question.answers.build }          end    end      # GET /surveys/1/edit    def edit      end      # POST /surveys    # POST /surveys.json    def create      @survey = Survey.new(survey_params)        respond_to do |format|        if @survey.save          format.html { redirect_to @survey, notice: 'Survey was successfully created.' }          format.json { render :show, status: :created, location: @survey }        else          format.html { render :new }          format.json { render json: @survey.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /surveys/1    # PATCH/PUT /surveys/1.json    def update      respond_to do |format|        if @survey.update(survey_params)          format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }          format.json { render :show, status: :ok, location: @survey }        else          format.html { render :edit }          format.json { render json: @survey.errors, status: :unprocessable_entity }        end      end    end      # DELETE /surveys/1    # DELETE /surveys/1.json    def destroy      @survey.destroy      respond_to do |format|        format.html { redirect_to surveys_url, notice: 'Survey was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_survey        @survey = Survey.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def survey_params        params.require(:survey).permit!      end      end  

surveys/_form.html.erb

<%= form_for(@survey) do |f| %>    <% if @survey.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>          <ul>        <% @survey.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>        <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>        <%= f.fields_for :questions do |builder| %>    <p>      <%= builder.label :content, "Question" %><br />      <%= builder.text_area :content, :rows => 3 %>    </p>       <%= f.fields_for :answers do |builder| %>    <p>      <%= builder.label :content, "Answer" %>      <%= builder.text_field :content %>    </p>    <% end %>     <% end %>           <div class="actions">      <%= f.submit %>    </div>  <% end %>  

surveys/show.html.erb

<p id="notice"><%= notice %></p>    <p>    <strong>Name:</strong>    <%= @survey.name %>  </p>    <ol>    <% @survey.questions.each do |question| %>    <li><%= question.content  %>    <ul>      <% for answer in question.answers %>      <li><%= answer.content %></li>      <% end %>    </ul>    </li>      <% end %>  </ol>      <%= link_to 'Edit', edit_survey_path(@survey) %> |  <%= link_to 'Back', surveys_path %>  

survey.rb:

class Survey < ActiveRecord::Base      has_many :questions, :dependent => :destroy      accepts_nested_attributes_for :questions, :reject_if => -> (a) {a[:content].blank? }, :allow_destroy => true  end  

question.rb:

class Question < ActiveRecord::Base      belongs_to :survey      has_many :answers, :dependent => :destroy      accepts_nested_attributes_for :answers, :reject_if => -> (a) {a[:content].blank? }, :allow_destroy => true  end  

answer.rb

class Answer < ActiveRecord::Base      belongs_to :question  end  

Any help would be appreciated, I've been stuck on this for hours now!

How do I prepend/append this div as the last child of all the children as opposed to the first?

Posted: 18 Jun 2016 02:38 AM PDT

So I have a view that has renders HTML that looks like this :

enter image description here

What is happening now is when the user adds a new comment, it is now added to the top of that list, i.e. the div.social-comment that is highlighted. However, I want it to be added after the last in the list, not as the first. How do I do that?

This is what the create.js.erb looks like:

$(".question-<%= @comment.commentable.id %>").prepend("<%= j (render partial: 'comments/comment', locals: { comment: @comment}) %>");  

How can I achieve what I want?

Edit 1

My bad, I wasn't fully clear with the original question.

I can't just use .append, due to the presence of a form field that is currently at the bottom of that list of children.

If I do use append, this is what the modified HTML looks like:

enter image description here

Note the .row .question-46-new appears before the last .social-comment.

So that ends up producing this:

screenshot-of-rendered-comments

Which is obviously what I don't want.

What I want is for the new comment to appear right above that Write Comment textbox, and at the end of the list of existing comments.

Edit 2

This is what my DOM tree looks like after attempting Pranav's suggestion:

enter image description here

why do we need a gemset in rails

Posted: 18 Jun 2016 06:20 AM PDT

I would like to understand a very basic concept in Ruby on Rails. Everytime I create a new rails application, I used to create a gemset and then install gems to that gemset. Once my friend asked me this question and I failed to make him understand very clearly.

Is it because if I have 2 projects under same ruby version & if both needs different versions of a particular gem . Suppose, Both are using default gemset, It can't install both versions of this gem to the default gemset as it cause conflict? Please correct me if am wrong .

Why is this index route raising RecordNotFound in deployment but works perfectly in development?

Posted: 18 Jun 2016 12:45 AM PDT

In a Rails app I have an index route that is working perfectly in development, but when pushed to deployment is raising an ActiveRecord::RecordNotFound error.

I am having trouble finding a systematic way to debug this because (a) I don't understand why an index would raise RecordNotFound; (b) the route works perfectly in development; and (c) I'm unsure where I should be looking to get useful logs/ reports from deployment to see what is going on.

The route in question:

#routes.rb  namespace :api, defaults: {format: 'json'} do    scope module: :v2, constraints: ApiConstraints.new(version: 2, default: :true) do      resources :states    end  end  

In development navigating to /api/states hits the api/v2/states controller and returns the correct output.

In deployment the same URL is hitting

#application_controller.rb  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found  

I tried adding some debug code to api_states_controller

def index      Rails.logger.info @states     # .....  end  

But of course this action is not being hit in deployment.

I also tried adding debug code to :record_not_found

def record_not_found    Rails.logger.info 'We are here'    flash[:alert] = "That page doesn't exist!"    redirect_to root_url  end  

Which is being raised, but I have not been able to find any variables available here that are telling me anything useful.

Why would an index be available in development, but raise RecordNotFound in deployment? And what is a sensible way to examine this problem?

Undefined method 'model_name' for nil:Nil Class

Posted: 18 Jun 2016 05:18 AM PDT

So i followed Ryan Bates Screencasts on using Paypal basic for payments and everything worked fine in development. However, when i deployed to Heroku and tried it. I got an Undefined method 'model_name' for nil:Nil.

It seems its breaking on the form_for in the cart page.

  <%= form_tag APP_CONFIG[:paypal_url] do %>    <% end %>  

For some reason, it is not loading the variable APP_CONFIG[:paypal_url]. I generated it using nifty:config as done in the tutorial.

The generated config file

development: &default  paypal_email: xxxxx@xxxx.com  paypal_secret: xxxxxx  paypal_cert_id: XXXXXXXXXXXXX  paypal_url: "https://www.sandbox.paypal.com/cgi-bin/webscr"    test:  <<: *default    production:  <<: *default  

The nifty:config also generated an initializer load_app_config.rb which looks like this >>

  raw_config = File.read("#{Rails.root}/config/app_config.yml")    APP_CONFIG = YAML.load(raw_config)[Rails.env].symbolize_keys  

Works in development, but not on Heroku. Am i doing something wrong?

Any help would be appreciated!

Thanks in Advance!

UPDATE:Backtrace

   Rendered customer/carts/show.html.erb within layouts/application (6.6ms)     2016-06-18T07:40:46.046130+00:00 app[web.1]: Completed 500 Internal Server                  Error in 27ms (ActiveRecord: 16.5ms)     2016-06-18T07:40:46.047088+00:00 app[web.1]:      2016-06-18T07:40:46.047099+00:00 app[web.1]:     38:      2016-06-18T07:40:46.047097+00:00 app[web.1]: ActionView::Template::Error     (undefined method `model_name' for nil:NilClass):     2016-06-18T07:40:46.047098+00:00 app[web.1]:     37:       <%= button_to          'Empty cart', @cart, action: 'destroy', method: :delete, data: { confirm: 'Are you   sure?' }, class: 'btn btn-default empty_cart btn_stand' %><br>     2016-06-18T07:40:46.047101+00:00 app[web.1]:     41:       <%= hidden_field_tag :size, value: :size %>     2016-06-18T07:40:46.047100+00:00 app[web.1]:     39:       <%= form_tag APP_CONFIG[:paypal_url] do %>     2016-06-18T07:40:46.047100+00:00 app[web.1]:     40:       <%= fields_for LineItem.find_by(params[:id]) do %>     2016-06-18T07:40:46.047101+00:00 app[web.1]:     42:       <%= hidden_field_tag :color, value: :color %>     2016-06-18T07:40:46.047104+00:00 app[web.1]:      2016-06-18T07:40:46.047103+00:00 app[web.1]:   app/views/customer/carts/show.html.erb:39:in `_app_views_customer_carts_show_html_erb__1117899742375249126_70196778419380'     2016-06-18T07:40:46.047102+00:00 app[web.1]:     43:       <% end %>     2016-06-18T07:40:46.047103+00:00 app[web.1]:   app/views/customer/carts/show.html.erb:40:in `block in _app_views_customer_carts_show_html_erb__1117899742375249126_70196778419380'  

Rails: first_or_initialize(id: 1) NoMethodError: undefined method `empty?' for 0:Fixnum

Posted: 18 Jun 2016 12:08 AM PDT

Running into an odd error while using first_or_initialize in my seeds

console> Model.where(association_id: 1).first  []    console> Model.where(association_id: 1).first_or_initialize(...)    > Model Load (0.8ms)  SELECT  "models".* FROM "models" WHERE     "models"."association_id" = $1  ORDER BY "models"."id"     ASC LIMIT 1  [["association_id", 0]]    NoMethodError: undefined method `empty?' for 0:Fixnum  

How do I use first_or_initialize with id?

Rails has_secure_token shorten character length

Posted: 17 Jun 2016 11:29 PM PDT

I am using the has_secure_token gem and I wish to shorten the token character length to 8. It is 24 by default. This is the link to the gem https://github.com/robertomiranda/has_secure_token

This token is associated with my Groups model. I was going through the gem's code and tried doing this in the groups_helper.rb but I had no luck. Thoughts on how to modify the token length? Apologies in advance if this is a simple fix but I am missing something here. Thanks.

 module GroupsHelper    def generate_unique_secure_token      SecureRandom.base58(4)    end   end  

Why is $(form).submit (e) firing multiple times?

Posted: 18 Jun 2016 12:11 AM PDT

I have the following coffeescript function in a rails app

if $(".my-form").length     $(".my-form").submit (event) ->      values = {}      $.each $(this).serializeArray(), (i, field) ->        values[field.name] = field.value        return      console.log(values)  

The console shows that, on form submit, this function is being run 4 times.

Object {utf8: "✓", my_form[my_field]: "my_value"}  Object {utf8: "✓", my_form[my_field]: "my_value"}  Object {utf8: "✓", my_form[my_field]: "my_value"}  Object {utf8: "✓", my_form[my_field]: "my_value"}  

To the best of my knowledge, there is not other code that would be interacting with this form. Is there an obvious reason why this function would be run multiple times? What should I be looking for to debug this? And what can I do to prevent this?

Rails - Query Composite Keys

Posted: 17 Jun 2016 11:22 PM PDT

I have a table in my database which uses composite keys. To implement it in rails, I used the gem 'composite_primary_keys' to implement this feature.

I have two primary keys - CompanyID, KeypersonID in the model CompanyKeyperson.

Now, if I want to find all the keypeople with CompanyID=1, how do I do it?

Something like -

    CompanyKeyperson.find(1,*)  

which obviously throws an error.

rails impressionist how to find 5 of most view item

Posted: 18 Jun 2016 07:09 AM PDT

I using this instance to find more view 5 Item, but cannot get the result.
Can teach me how to get it?

 @test = Item.limit(5).joins(:impressions).group("impressions.impressionable_id").order("count(impressions.impressionable_id) DESC")  

nested fields_for not showing up in forms

Posted: 17 Jun 2016 11:20 PM PDT

Everything looks great as far as I can tell -- but the contents for the field_for nested form aren't displaying the 3 question forms I want. Why?

survey.rb

class Survey < ActiveRecord::Base      has_many :questions, :dependent => :destroy      accepts_nested_attributes_for :questions  end  

question.rb

class Question < ActiveRecord::Base      belongs_to :survey  end  

surveys_controller.rb

class SurveysController < ApplicationController    before_action :set_survey, only: [:show, :edit, :update, :destroy]      # GET /surveys    # GET /surveys.json    def index      @surveys = Survey.all    end      # GET /surveys/1    # GET /surveys/1.json    def show    end      # GET /surveys/new    def new      @survey = Survey.new      3.times { @survey.questions.build }    end      # GET /surveys/1/edit    def edit    end      # POST /surveys    # POST /surveys.json    def create      @survey = Survey.new(survey_params)        respond_to do |format|        if @survey.save          format.html { redirect_to @survey, notice: 'Survey was successfully created.' }          format.json { render :show, status: :created, location: @survey }        else          format.html { render :new }          format.json { render json: @survey.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /surveys/1    # PATCH/PUT /surveys/1.json    def update      respond_to do |format|        if @survey.update(survey_params)          format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }          format.json { render :show, status: :ok, location: @survey }        else          format.html { render :edit }          format.json { render json: @survey.errors, status: :unprocessable_entity }        end      end    end      # DELETE /surveys/1    # DELETE /surveys/1.json    def destroy      @survey.destroy      respond_to do |format|        format.html { redirect_to surveys_url, notice: 'Survey was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_survey        @survey = Survey.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def survey_params        params.require(:survey).permit(:name)      end  end  

surveys/new.html.erb

<h1>New Survey</h1>    <%= render 'form' %>    <%= link_to 'Back', surveys_path %>  

surveys/_form.html.erb

<%= form_for(@survey) do |f| %>    <% if @survey.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>          <ul>        <% @survey.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>        <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>        <% f.fields_for :questions do |builder| %>    <p>      <%= builder.label :content, "Question" %><br />      <%= builder.text_area :content, :rows => 3 %>    </p>    <% end %>           <div class="actions">      <%= f.submit %>    </div>  <% end %>  

No comments:

Post a Comment