Sunday, December 4, 2016

Custom Controller Method, Route, & ERB | Fixed issues

Custom Controller Method, Route, & ERB | Fixed issues


Custom Controller Method, Route, & ERB

Posted: 04 Dec 2016 07:52 AM PST

I have a search form and I need to be able to filter based on whether or not pets are allowed, but I'm not sure how to accomplish this. I have setup a route, a controller method, and a button but none of that seems to be working.

listings_controller:

def pets_allowed    @listings = @listings.where(pets: true)  end  

routes.rb:

  get "pets_allowed" => "listings#pets_allowed"  

html.erb file:

<div>    <%= link_to 'Pets Allowed', pets_allowed_path, :class => 'button btn-transparent' %>  </div>  

Rails 5 - how to dynamically add nested fields in the edit form?

Posted: 04 Dec 2016 07:48 AM PST

Already a month trying to solve the problem at first sight is not very complicated: There are 3 models - team, user and team_user (has_namy: through) In the form of edit and new team to do the ability to dynamically add members of this team. Scenario: - A user comes to the team new form - Indicates the name of the team - After name field select user (team member) - Click the Add member button - After validation of a member is added after team's name field in text field + delete button opposite - From the selector delete his (member) name (as it is already a team member) - In selite selects the next user, and click the Add member button - Press the Submit button to save the new team and team's members

Difficulties: - I tried to do through the gem Cocoon, but it is impossible to make different parshaly to select the user to be added to it (SELECT) and has added members (full name - text) - If done through the <% = from_for ... remote: true%> and a separate controller or new action in the controller teams_controller, it will be two forms of nested (shape and form team team_user) with his 2nd submit button. Attachment forms, as I understand, is not gud. - Changes in the form (changing the name of the team and add / remove the team members have the count only after clicking on the save to basically submit the form team)

enter image description here

Faraday::ConnectionFailed after resetting my cable modem

Posted: 04 Dec 2016 07:49 AM PST

I have (or had) omniauth-google-oauth2 successfully working in my rails app until this morning. My internet provider was briefly down and I also reset my cable modem. Now I get the following error after attempting to secure permission from google:

Faraday::ConnectionFailed    execution expired    878 s = Timeout.timeout(@open_timeout, Net::OpenTimeout) {  879  begin  880     TCPSocket.open(conn_address, conn_port, @local_host, @local_port)  881  rescue => e  882     raise e, "Failed to open TCP connection to " +  883      "#{conn_address}:#{conn_port} (#{e.message})"  

And Line 880 is highlighted in the message. Any ideas?

Unable to redirect from user edit page using devise gem

Posted: 04 Dec 2016 07:30 AM PST

I am using devise gem version 4.1.1 in my rails project and in my /users/edit page I want to redirect to the same page after the user changes his password instead of redirecting to the root_path. I googled around and found this link devise github wiki

I did make the changes accordingly and my registrations controller is as follows

class RegistrationsController < Devise::RegistrationsController      protected      def after_update_path_for(resource)      edit_user_registration_path    end  end  

and in routes.rb I added the registrations controller

devise_for :users, controllers: { confirmations: "confirmations", registrations: "registrations"}  

But still for some reason I am not able to redirect to the same page and it still redirects to root_path. Am I missing something?

Rails: why emails are sent before Users submit the form?

Posted: 04 Dec 2016 07:24 AM PST

I have a "Static form" that sends pricelists to clients, I need to send an email but params[:pricelist_name] from the form is nil.

I noticed that emails are sent before the view, so I was wondering how to send emails only after that users submit the form ?

Cheers,

Controller

  def sendpricelist      @pricelist = params[:pricelist_name] || []      @request_id = params["pricelist_name"] || []      @test = "test"      SaasMailer.pricelist_request_email(@pricelist, @test, @request_id).deliver_now      #redirect_to :requests  end  

View

    <%= form_tag(:controller => "requests", :action => "sendpricelist") do %>    <%= text_field(:post, :title, size: 69, class: 'form-control form-group-lg') %>      <%= select_tag 'pricelist_name',     options_from_collection_for_select(Pricelist.all, :id, :name) %>          <%= submit_tag("Send pricelist")%>        <% end %>  

Routes

 devise_for :users   resources :users   resources :requests do   resources :updates  match '/sendpricelist',      to: 'requests#sendpricelist',           via: 'get'    end  

Output:

As you can see in 'Subject: [] - [] - test' params are nil.

Started GET "/requests/12/sendpricelist" for 127.0.0.1 at 2016-12-04 15:20:45 +0000  Processing by RequestsController#sendpricelist as HTML    Parameters: {"request_id"=>"12"}    Rendered saas_mailer/pricelist_request_email.html.erb within layouts/mailer (0.2ms)    SaasMailer#pricelist_request_email: processed outbound mail in 19.6ms    Sent mail to remyukjob@gmail.com (2012.5ms)  Date: Sun, 04 Dec 2016 15:20:45 +0000  From: from@example.com  Reply-To: remyukjob@gmail.com  To: remyukjob@gmail.com  Message-ID: <5844344d7cc60_23a33f8f3527db9467454@remy-Aspire-ES1-512.mail>  Subject: [] - [] - test  Mime-Version: 1.0  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: quoted-printable    <html>    <body>      <!DOCTYPE html>  <html>    <head>      <meta content=3D'text/html; charset=3DUTF-8' http-equiv=3D'Content-Ty=  pe' />    </head>    <body>      <h1><img src=3D"https://ci4.googleusercontent.com/proxy/HzK8rp8AJ2iFz=  l3q5Z2jtTKO4tCzMTfOJ9WT7CAzSVpHdXm676yMNYhbZzgrNSjFyzkChWQRdKCSZe7M-xrt6q=  IRl5wXoecqdqR3gUOINxF9CnwQoFC2YGQyG7FhdTAcWS9FNwRTDDh2KOkvTGxOOXOc=3Ds0-d=  -e1-ft#http://www.sweetconcepts.com/wp-content/themes/twentysixteen-child=  /assets/images/sc_logo.jpg" alt=3D"Sc logo" /></h1>      <p>        Bonjour Sandrine,      </p>         <p>        Merci pour votre demande  nil.        <br></br>        J=E2=80=99ai joint en pi=C3=A8ce jointe les pricelists pour :      </p>          Pricelisttitle <a href=3D"https://s3.amazonaws.com/promosweetsdocs/=  Confirmation.pdf">Lien</a> =          </body>  </html>    </body>  </html>      Pricelist Load (0.3ms)  SELECT "pricelists".* FROM "pricelists"    Rendered requests/sendpricelist.html.erb within layouts/application (18.6ms)  Completed 200 OK in 2228ms (Views: 134.3ms | ActiveRecord: 2.8ms)      Started POST "/requests/12/sendpricelist" for 127.0.0.1 at 2016-12-04 15:20:51 +0000  

Rails 5 starting thread from initializer gone crazy

Posted: 04 Dec 2016 06:31 AM PST

I have the following code in config/application.rb:

config.after_initialize do    MyConcern.init_processing  end  

Then the following related methods:

def init_processing    @queue_processor = Thread.new do      process_op_queue    end    @queue_processor.name = "Some Queue"    # @queue_processor_notifier = Queue.new  end    def process_op_queue    while true      req = MyRequest.where(done: Helper::FALSE_NIL_OR_MISSING, started_at: nil).order_by(id: :asc).find_one_and_update({'$currentDate' => {started_at: true}}, return_document: :after)      req ? process_queue_item(req) : sleep(30)    end  end  

Basically starting a thread on server startup to perform some background tasks that are accepted by the app from users by HTTP calls.

In development mode everything works fine. Running in production env with same puma server, the @queue_processor shows dead (from rails console):

MyConcern.instance_variable_get("@queue_processor").join  => #<Thread:0x00000002b8fa68@MyConcern Queue@/var/lib/openshift/5842d71a5110e25cdf00000c/app-root/runtime/repo/app/controllers/concerns/my_concern.rb:23 dead>   MyConcern.instance_variable_get("@queue_processor").value  => false  

First it is (mildly said) non-obvious to me how a thread can die without an exception and returning false with the loop that I have above in process_op_queue. The other very interesting facts are that:

  1. there is actually a thread doing the work as obvious to me while doing requests to the app and looking at what changes in the database
  2. in rails console I see only one thread:

.

2.3.1 :009 > Thread.list   => [#<Thread:0x000000012f63a8 run>]   2.3.1 :010 >   

Part of the app is checking the queue processor thread and reporting errors with it so showing up as dead is really breaking that logic. Any advises how to debug and resolve the issue would be appreciated. Thank you.

Getting data from many to many relation with rails 4

Posted: 04 Dec 2016 07:07 AM PST

I am developing a rails app with mysql database.

Theres bunch of tables but for this task I am using only 3. Students, Courses and CoursesPerStudent.

I have models for students and courses(no model for the third). The tables are already populated.

The tables:

students - id,name,family,address,phone,email,status,path
courses - courseCode, courseName, hours
coursesperstudent - code, student(same ids as in students table ids but not a oreign key),path,course(courses table code(foreign key)),examMark.

Now the thing is i need to show for each student a list of the courses realted to him.

How should i do it? Should i create model for the third table? how should i call it? and combine the two other tables in one to show specific courses?

Or there some other way?

Hopefully someone will help because im out of answers.

Error while rendering a form in different controller

Posted: 04 Dec 2016 05:21 AM PST

I'm trying to render a form app/views/requestforpms/_form.html.erb in app/views/passengerrides/show.html.erb, but getting an error First argument in form cannot contain nil or be empty at <%= form_for @requestforpm do |form| %>.

app/views/passengerrides/show.html.erb:

<%= render partial: 'requestforpms/form' %>  

app/views/requestforpms/_form.html.erb:

<%= form_for @requestforpm do |form| %>     <%= form.hidden_field :passengerride_id, :value => @passengerride.id %>     <%= form.hidden_field :customer_id, :value => @current_user.id %>     <%= form.hidden_field :status, :value => 'Request' %>     <%= form.submit %>  <% end %>  

apps/controller/requestforpms_controller.rb:

class RequestforpmsController < ApplicationController    before_action :set_requestforpms, only: [:show, :edit, :update, :destroy]     def create    @passengerride =  Passengerride.find (params[:passengerride_id])    @requestforpm = @passengerride.requestforpms.new(requestforpm_params)      respond_to do |format|     if @requestforpm.save      format.html { redirect_to @passengerride, notice: 'Comment was successfully created.' }      format.json { render json: @requestforpm, status: :created, location: @requestforpm }     else      format.html { render :new }      format.json { render json: @requestforpm.errors, status: :unprocessable_entity }     end    end   end     private    def set_requestforpms     @requestforpm = Requestforpm.find(params[:id])    end        def requestforpms_params     params.require(:requestforpm).permit(:passengerride_id, :customer_id, :status)    end  end  

Edit:

apps/controller/passengerrides_controller.rb:

class PassengerridesController < ApplicationController     before_action :para_passengerride, only: [:edit, :update, :show]   load_and_authorize_resource :except => :create     def index    @q = Passengerride.ransack(params[:q])    @passengerrides = @q.result(distict: true)   end     def new    @passengerride = Passengerride.new   end     def show   end     def edit   end    def create     @passengerride = Passengerride.new(passengerride_params)   @passengerride.user = current_user   if @passengerride.save    flash[:success] = 'Ride was successfully created.'    redirect_to passengerride_path(@passengerride)   else    render 'new'   end  end    def update     @passengerride.user = current_user   if @passengerride.update(passengerride_params)    flash[:success] = 'Ride was successfully updated'    redirect_to passengerride_path(@passengerride)   else    render 'edit'   end  end      def destroy   @passengerride = Passengerride.find(params[:id])   @passengerride.destroy   flash[:danger] = "Ride has been deleted successfully"   redirect_to passengerrides_path  end    private     def para_passengerride    @passengerride = Passengerride.find(params[:id])   end    private     def passengerride_params    params[:passengerride][:sharegasmoney] = params[:passengerride][:sharegasmoney].join(', ')    params[:passengerride][:okwithgender] = params[:passengerride][:okwithgender].join(', ')    params[:passengerride][:okwith] = params[:passengerride][:okwith].join(', ')    params.require(:passengerride).permit(:origin, :destination, :departuretime, :departuredate, :okwithgender, :okwith, :sharegasmoney, :description)   end  

end

How to enter passphrase for ssh key while deploy rails app via Capistrano?

Posted: 04 Dec 2016 05:37 AM PST

I tried to deploy my app to digital ocean server following this tutorial.

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

So i can clone my apps successfully but when deployed the production one it required me to enter passphrase but when i type it in my terminal it seems like nothing happened like this

cap production deploy:initial  deploy@xxxxxx's password:   deploy@xxxxxx's password:   rvm 1.27.0 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]  ruby-2.3.0  ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]  00:00 git:wrapper        01 mkdir -p /tmp      ✔ 01 deploy@139.59.235.223 0.080s        Uploading /tmp/xxxx.sh 100.0%        02 chmod 700 /tmp/xxxx.sh      ✔ 02 deploy@139.59.235.223 0.088s  00:00 git:check        01 git ls-remote --heads git@bitbucket.org:xxxx/xxxx.git        01 Enter passphrase for key '/home/deploy/.ssh/id_rsa':  password101  passwordyololo  howtotypepassword  

So how can i enter the passphrase in my terminal and pass this kind of security?

Thanks!

Finding free appointment slots from appointment table Postgresql Rails

Posted: 04 Dec 2016 04:07 AM PST

I have an app in ruby on rails that has Appointments which belong to Providers and I am looking to create a query that finds a provider's gaps in appointments Appointments are stored as a start and finish both which are datetimes . Ideally I would call Provider.free_appointment_slots(length,start,finish) where length is the length of the appointment required and start and finish are bounds of the search ie a particular week or day.

I think it should be somewhat similar to these... How to return all the free periods of time from an appointment set Finding free blocks of time in mysql and php?

I have an appointments table with data like:

ID    |       Start       |       Finish       | ProviderID  1       2016-11-12 09:00    2016-11-12 09:30        1  1       2016-11-12 10:00    2016-11-12 10:30        1  1       2016-11-12 11:30    2016-11-12 12:00        1  

etc

I would like to be able to provide a start and end time to search over and an appointment length and my query return the available appointment times.. for example If I was looking for appointments between 2016-11-12 08:30 and 2016-11-12 12:30 with an appointment length of 30min

I would receive results such as:

     Start       |     Finish  2016-11-12 08:30   2016-11-12 09:00  2016-11-12 09:30   2016-11-12 10:00  2016-11-12 10:30   2016-11-12 11:00  2016-11-12 11:00   2016-11-12 11:30  2016-11-12 12:00   2016-11-12 12:30  

an additional great feature would be to be able to provide multiple search periods such as over different days

I hope this is clear any help would be much appreciated

Having trouble in updating join model extra attributes in has_many through association - Rails

Posted: 04 Dec 2016 05:51 AM PST

I am still a learner of Rails, and am making a simulation game of Google Adwords for training usage. Inside the game (I may only explain the related part of this question), I have three models, Adgroup (called KeywordAdgroup in my code), Keyword, AdgroupKeyword, and also a Game model that has a game_id in it.

The relationship of the three models is a has_many through: assciation, which Adgroup has many Keywords through AdgroupKeyword, and Keyword has many Adgroups through AdgroupKeyword.

Now, I want to adopt a logic that every Keyword could only be added into single Adgroup of a particular game. So I added an extra attribute game_id to the join model - AdgroupKeyword, and adopt validates_uniqueness_of :keyword_id, scope: :game_id into this model.

However, I found that with the similar code, I can validate the uniqueness in Create using .save method, but I can't validate the uniqueness in Update using .update(params) method.

The major problem is that, with the similar code in create and update, the create one can save the game_id to the join model(AdgroupKeyword), where update(params) didn't save the game_id to the join model, which in the console, I can see that update didn't insert game_id into the record.

It will become something like game_id: nil:

#<AdgroupKeyword id: 180, keyword_id: 9, created_at: "2016-12-04 11:12:00", updated_at: "2016-12-04 11:12:00", keyword_adgroup_id: 77, game_id: nil>  

But the save method did insert the game_id, which game_id is not nil when inserted using the save method. Something like

#<AdgroupKeyword id: 174, keyword_id: 10, created_at: "2016-12-04 10:23:50", updated_at: "2016-12-04 10:23:50", keyword_adgroup_id: 77, game_id: 3>  

The following is my code:

keyword_adgroup.rb (the model of Adgroup)

class KeywordAdgroup < ApplicationRecord    belongs_to :keyword_campaign      has_many :adgroup_keywords, inverse_of: :keyword_adgroup, dependent: :destroy    has_many :keywords, through: :adgroup_keywords, source: :keyword    accepts_nested_attributes_for :adgroup_keywords, allow_destroy: true      ...      accepts_nested_attributes_for :keywords      ...      ...  end  

keyword.rb

class Keyword < ApplicationRecord    ...      ...      has_many :keyword_adgroups, through: :adgroup_keywords    has_many :adgroup_keywords      ...  end  

adgroup_keyword.rb(the join model)

class AdgroupKeyword < ApplicationRecord    belongs_to :keyword_adgroup    belongs_to :keyword      validates_uniqueness_of :keyword_id, scope: :game_id    end  

And majorly the relation would be built in the Adgroup controller.

adgroups_controller.rb

class Adwords::AdgroupsController < AdwordsController      def index      ...    end      def new      @adgroup = KeywordAdgroup.new    end      def create      @campaign = current_user.game.keyword_campaigns.find(params[:keyword_campaign_id])      @adgroup = @campaign.keyword_adgroups.build(adgroup_params)      @adgroup.game_id = @campaign.game_id      @adgroup.adgroup_keywords.each do |join|        join.game_id = @adgroup.game_id          end        if @adgroup.save        redirect_to new_adwords_ad_path(keyword_adgroup_id: @adgroup.id)      else        render :new      end    end      def edit      @adgroup = KeywordAdgroup.find(params[:id])    end      def update      @adgroup = KeywordAdgroup.find(params[:id])      @campaign = @adgroup.keyword_campaign      @adgroup.game_id = @campaign.game_id      @joins = @adgroup.adgroup_keywords      @joins.each do |join|        join.game_id = @adgroup.game_id        end       if @adgroup.update(adgroup_params)          redirect_to adwords_adgroups_path, notice: "Adgroup updated"      else        render :edit      end    end      ...      private    def adgroup_params      params.require(:keyword_adgroup).permit(:name, :activate, :bid, keyword_ids: [], adgroup_keywords_attributes: [:game_id])    end    end  

When choosing duplicate keyword in the same game in whatever adgroup, in "create", it will come to a rollback; in "update", it will just update the record with game_id: nil.

FYI, I am using Ruby 2.3.0, Rails 5.0.0, and using simpleform for creating and updating adgroup.

I know its a little bit messy, sorry about that and thanks for reading my words. Appreciate any suggestions. Have already spent several hours to fix it but really hopeless after a lot of different methods. Thought that it was some conceptual problem that I haven't figured out.


Updated Information

While checking the console, in "Create" method, it will come to:

  AdgroupKeyword Exists (0.4ms)  SELECT  1 AS one FROM "adgroup_keywords" WHERE "adgroup_keywords"."keyword_id" = ? AND "adgroup_keywords"."game_id" = ? LIMIT ?  [["keyword_id", 14], ["game_id", 3], ["LIMIT", 1]]    Keyword Exists (0.3ms)  SELECT  1 AS one FROM "keywords" WHERE "keywords"."keyword" = ? AND ("keywords"."id" != ?) LIMIT ?  [["keyword", "Japan local trip"], ["id", 14], ["LIMIT", 1]]    KeywordAdgroup Exists (0.2ms)  SELECT  1 AS one FROM "keyword_adgroups" WHERE "keyword_adgroups"."name" = ? AND "keyword_adgroups"."keyword_campaign_id" = ? LIMIT ?  [["name", "3"], ["keyword_campaign_id", 36], ["LIMIT", 1]]    SQL (2.3ms)  INSERT INTO "keyword_adgroups" ("name", "activate", "bid", "created_at", "updated_at", "keyword_campaign_id", "game_id") VALUES (?, ?, ?, ?, ?, ?, ?)  [["name", "3"], ["activate", true], ["bid", #<BigDecimal:7fcaac52c320,'0.1E1',9(18)>], ["created_at", 2016-12-04 13:10:19 UTC], ["updated_at", 2016-12-04 13:10:19 UTC], ["keyword_campaign_id", 36], ["game_id", 3]]    SQL (0.2ms)  INSERT INTO "adgroup_keywords" ("keyword_id", "created_at", "updated_at", "keyword_adgroup_id", "game_id") VALUES (?, ?, ?, ?, ?)  [["keyword_id", 14], ["created_at", 2016-12-04 13:10:19 UTC], ["updated_at", 2016-12-04 13:10:19 UTC], ["keyword_adgroup_id", 84], ["game_id", 3]]    AdgroupKeyword Exists (0.3ms)  SELECT  1 AS one FROM "adgroup_keywords" WHERE "adgroup_keywords"."keyword_id" = ? AND ("adgroup_keywords"."id" != ?) AND "adgroup_keywords"."game_id" = ? LIMIT ?  [["keyword_id", 14], ["id", 187], ["game_id", 3], ["LIMIT", 1]]  

In "Update" method, it will come to:

  AdgroupKeyword Exists (0.2ms)  SELECT  1 AS one FROM "adgroup_keywords" WHERE "adgroup_keywords"."keyword_id" = ? AND "adgroup_keywords"."game_id" IS NULL LIMIT ?  [["keyword_id", 17], ["LIMIT", 1]]    SQL (2.0ms)  INSERT INTO "adgroup_keywords" ("keyword_id", "created_at", "updated_at", "keyword_adgroup_id") VALUES (?, ?, ?, ?)  [["keyword_id", 17], ["created_at", 2016-12-04 13:07:03 UTC], ["updated_at", 2016-12-04 13:07:03 UTC], ["keyword_adgroup_id", 82]]    AdgroupKeyword Exists (0.2ms)  SELECT  1 AS one FROM "adgroup_keywords" WHERE "adgroup_keywords"."keyword_id" = ? AND ("adgroup_keywords"."id" != ?) AND "adgroup_keywords"."game_id" = ? LIMIT ?  [["keyword_id", 11], ["id", 185], ["game_id", 3], ["LIMIT", 1]]  

Background image in inline CSS code doesn't show when ran in rails server

Posted: 04 Dec 2016 05:47 AM PST

I am editing my landing page for my web. I am currently using Rails 5 to develop my web. I have this css block here (I am using bootstrap as well):

     <div class="item">                    <!-- Set the second background image using inline CSS below. -->                   <div class="fill" style="background-image:url('images/1.png');"></div>                  <div class="carousel-caption">                      <h1 class="light mab-none">This is <strong class="bold-text">art</strong></h1>                      <h1 class="light margin-bottom-medium mat-none">And We Are <strong class="bold-text">Awesome</strong></h1>                      <p class="light margin-bottom-medium">Stop blending in & start leaving your mark on the web.</p>                      <div class="call-button">                          <div class="row">                              <div class="col-md-4 col-md-offset-2 col-sm-4 col-sm-offset-2 col-xs-12">                                  <a href="#portfolio" class="button pull-right internal-link bold-text light hvr-grow" data-rel="#portfolio">Our Work</a>                              </div>                              <div class="col-md-4 col-sm-4 col-xs-12">                                  <a href="#about-us" class="button pull-left internal-link bold-text main-bg hvr-grow" data-rel="#about-us">About Us</a>                              </div>                              <div class="clearfix"></div>                          </div>                      </div>                  </div>                  <div class="overlay"></div>              </div>  

However, when I start my rails server, only the texts appear and the background image don't.

Do take note that I am doing this inside a layout in my rails project folder. All assets (images, css, js, etc) are all in my assets folder. As for my images, they are all inside the images folder under assets.

Adding superuser to GitLab on Debian Jessie repository installation

Posted: 04 Dec 2016 03:36 AM PST

I've installed GitLab via debian jessie-backports and it installed fine but there was no prompt to create superuser account. I tried to add it manually, but every solution on the Internet use

gitlab-rails  

which seems to be absent in my system.

Is there any way to add superuser without relying on gitlab-rails tool?

Updating unique constraint index after deleting records

Posted: 04 Dec 2016 03:19 AM PST

So I've got a postgres database full of users

create_table :users do |t|    t.string :subdomain    t.index [:subdomain], name: "index_users_on_subdomain", unique: true, using: :btree  end  

One of them deletes their account by mistake and wants to sign up again. But a validation error is called. Even though the record itself was deleted, the subdomain still exists in the index

duplicate key value violates unique constraint "index_users_on_subdomain"  

This feels like a bug to me. Shouldn't the index be updated in the after_destroy callback? Am I expected to manually drop and add the index each time someone removes their account?

Any ideas?

Rails 5 api - undefined method `user_url'

Posted: 04 Dec 2016 05:31 AM PST

I started a new project with Rails 5 in API mode.

For the moment i just create the project, set the database and use the scaffold command.

rails g scaffold User  

I try my code with postman to create a new user (POST)

Request

URI localhost:3000/v1/users  {      "first_name": "Firstname",      "last_name": "Lastname",      "email": "anemail@gmail.com32"  }  

Result

#<NoMethodError: undefined method `user_url' for #<Api::V1::UsersController:0x005594d8a4ad90>  

How can i fix that error ?

routes.rb

Rails.application.routes.draw do    scope module: 'api' do      namespace :v1 do        resources :users, :as => 'user'      end    end  end  

users_controller.rb

# POST /users  def create    @user = User.new(user_params)      if @user.save      render json: @user, status: :created, location: @user    else      render json: @user.errors, status: :unprocessable_entity    end  end  

React Native and Rails [on hold]

Posted: 04 Dec 2016 02:17 AM PST

I would like to write in first case a wep app. I am working since almost 2 years now with Rails and I like it very much. My views are always done by myself, which worked so far very good. Now I would like to expand my horizon. I want to differentiate frontend and backend. Why? Because my web app should me available as native app on iOS and Android too. So I thought I will use: http://edgeguides.rubyonrails.org/api_app.html as my backend. So everything responded as JSON. For building user interfaces and the web view I though React from Facebook would good. Because as soon as I decide to write an app I could use React Native for this purpose. So What do you think about this combination? Is this worth a try?

Address already in use - bind(2) for "::1" port 3000 (Errno::EADDRINUSE)

Posted: 04 Dec 2016 02:40 AM PST

enter image description here

When I type rails server in my macpro macos sierra,10.12,ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16],ails 5.0.0.1, I got the outcome as the picture shown, I don't know why, because the first do this ,there is nothing wrong.

How to use jekyll on an existing blog made with rails

Posted: 04 Dec 2016 02:33 AM PST

My situation is that I have just finished creating a blog using ruby on rails. I have been using localhost to see it display on my browser, but I want to deploy it online. I found out that rails apps can't be deployed on ghpages because it is not static. However, I searched online and read that if I used Jekyll, i could display it on ghpages. I have never used jekyll before, so my question is...

How could I use/integrate jekyll to my existing rails app so that it can be deployed and hosted through github pages?

Thank you!

Radio buttons in a form_tag that are styled with bootstrap

Posted: 04 Dec 2016 01:22 AM PST

I have the following radio buttons that are styled with bootrstrap:

    <tr>        <div class="btn-group" data-toggle="buttons">          <label class="btn btn-default active">            <input type="radio" name="options" id="option1" autocomplete="off" checked> Applied          </label>        </div>      </tr>  

How do I include this in a form_tag?

<%= form_tag "/update_application_status" do %>    <%= submit_tag "Update", class: "btn btn-primary" %>  <% end %>  

AngularJS $resource save success function not getting data

Posted: 03 Dec 2016 11:56 PM PST

I am building an application with Rails 5.0.0 with my back-end (api-only mode) and AngularJS as front-end.

While testing on my localhost API in POSTMAN, I hit the POST endpoint - http://localhost:3000/sessions.json?session[email]=shahravi@gmail.com&session[password]=foobar

and receive -

{    "id": 1,    "name": "Ravi Shah",    "email": "shahravi@gmail.com"  }  

with status 200 from rails server - "Completed 200 OK in 120ms"

I am using Active Model Serializer to get this response back through -

render json: user, status: :ok  

inside my rails controller.

However, inside my front-end angular code, when I hit the same endpoint, the $resource $save function does not execute the success callback. It gets the following data back from the endpoint in the error callback -

{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"data":{"session":{"email":"shahravi@gmail.com","password":"foobar"}},"url":"http://localhost:3000/sessions.json","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":""}  

My angular code is written as -

sessionResource = new LoginResource({session: {email: $scope.email, password:$scope.password}});  sessionResource.$save(function(success){            console.log("Login success" + JSON.stringify(success));            $state.transitionTo('dashboard');            return true;          }, function(error){            console.log("Login error - " + JSON.stringify(error));          });   

where LoginResource is defined as -

angular.module('SampleApp').factory('LoginResource', function($resource){              return $resource('http://localhost:3000/sessions/:id.json', {id: '@id'}, {'update': {method:'PUT'}});      });  

Can somebody help figure out where the problem is? Why does rails server return success with right data, but angular does not get success code or the data?

pg_search dmetaphone not working after installing contrib package

Posted: 03 Dec 2016 11:41 PM PST

After installing pq_search and running contrib package migration:

class InstallSomeContribPackages < ActiveRecord::Migration    def up      execute 'CREATE EXTENSION pg_trgm;'      execute 'CREATE EXTENSION fuzzystrmatch;'    end      def down      execute 'DROP EXTENSION pg_trgm;'      execute 'DROP EXTENSION fuzzystrmatch;'    end  end  

It still throws error when migrating the dmetaphone migration:

PG::UndefinedFunction: ERROR:  function dmetaphone(text) does not exist  LINE 2:   SELECT array_to_string(ARRAY(SELECT dmetaphone(unnest(rege...  

How to disable sending default emails when a user place an order?

Posted: 03 Dec 2016 11:46 PM PST

I am working on a Third party application where I want to send customized template emails to user using webhooks when user place order or shipment gets created.

Is it possible to prohibit system to send email to user who place order and instead of that just fire an event to a third party app(using a webhook) so that that third party app will send email to that user with required and customized new details in new email template(which is not available in default variables of email templates)?

Any solution for this? Please

Ruby on Rails sample project

Posted: 03 Dec 2016 11:19 PM PST

I'm looking for a sample project online which I can follow to create my startup project. I'm fairly new to RoR and created some simple projects. Here is what I'm looking for: Admin side: -Create, edit, and delete user account -Post new payable/amount to particular user (e.g. billing)

User side: -Login and change password (with the use of Devise gem) -Manage payments, can pay new posted payabale (Stripe or Paypal) -View payment history

They system will send email notification to user for new payable, as well as when they submit the payment.

There should be two tables, users and payables (one-to-many), users can have more than one payable.

Please let me know where can I find a sample project. Thanks.

Importing namespaced files in a controller

Posted: 03 Dec 2016 10:59 PM PST

I have the following files:

/lib/stripe/stripe_invoice.rb

class StripeInvoice  ...  end  

Now in my controller I am trying to use it:

def index          si = StripeInvoice.new(...)    end  

I get an error for uninitialized constant StripInvoice.

If I add:

require 'lib/stripe_invoice'  

I get the error:

cannot load such file -- lib/stripe_invoice  

What is the correct way to import my class file so I can use it in my controller?

Also, how can I create a namespace for my class StripeInvoice and how would that change the way I import it?

advance table search in rails

Posted: 04 Dec 2016 12:54 AM PST

In my app i have generated a scaffold called data and had filed the table with name, school, college, views, interest. Now i want to add a search that if someone put NAME in the search bar, they should get all the names only as results, if someone had put college, they should get all the college only.

Am pretty new to rails, so i tried watching some tutorials, and had added this but this is not what i want

<%= form_tag data_path, :method => 'get' do %>  <%= text_field_tag :search, params[:search] %>  <%= submit_tag "Search" %>  <% end %>  

in controller

  def index      @data = Datum.where (["name LIKE ?", "%#{params[:search]}%"])    end  

This had added a search but not the type of search i had mentioned above.

Apartment Gem Ruby on rails redirect to the home page of heroku

Posted: 03 Dec 2016 06:27 PM PST

I'm using the Apartment gem in ruby on rails to work with multitenancy and in local host works fantastic, but I did deploy to heroku and I get redirect to the main page of heroku

enter image description here

I have my own domain but when I visit my domain just says:

This website is temporarily unavailable, please try again later.

so I dont know what to do, I need to use amazon ? you know some configuration guys ?

Regards ! and thanks for your time !

Integrating Paypal button with Rails

Posted: 03 Dec 2016 05:53 PM PST

I am trying to integrate Paypal in my rails application by generating a hosted button from paypal. I am following the following guide https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/buy_now_step_1/ but I cannot find a way to dynamically generate a buy now button with custom prices and description without first creating it through paypal.com.

My question is is there a way to generate the buttons dynamically from my database of items so that they don't have to be first created through paypal.com manually.

or

Is there a better way to do this? I'm new to both rails and paypal API.

ActiveRecord has_many where child model is greater than 0

Posted: 04 Dec 2016 01:46 AM PST

I'm trying to solve a seemingly simple AR problem I'm having. I can't figure out how to return a list of events that have 1 or more attendees, and the docs examples use cache_control which I don't want to use.

I have a simple event model with a has_many relationship:

class Event < ActiveRecord::Base    has_many :attendees  end  

and an attendees model that belongs to event

class Attendees < ActiveRecord::Base    belongs_to :event  end  

But some events will have 0 attendees. So what's the ActiveRecord way of doing this without using cache_control or writing a custom SQL statement?

It seems like it would be something like:

Event.where(attendees.count > 0)

but I keep getting a column error.

Rails Devise Recoverable - Not receiving forgot your password e-mail

Posted: 03 Dec 2016 04:11 PM PST

source 'https://rubygems.org'  ruby '2.3.1'    gem 'rails',                   '5.0.0'  gem 'pg'  gem 'devise',                  '~> 4.2'  gem 'bcrypt',                  '3.1.11'  gem 'faker',                   '1.6.3'  gem 'will_paginate',           '3.1.0'  gem 'bootstrap-will_paginate', '0.0.10'  gem 'bootstrap-sass',          '3.3.6'  gem 'puma'  gem 'uglifier',                '3.0.0'  gem 'coffee-rails',            '4.1.1'            gem 'turbolinks',              '5.0.0.beta2'  gem 'jbuilder',                '2.4.1'  gem 'gon',                     '~> 6.0', '>= 6.0.1'  gem 'filepicker-rails',        '~> 2.1'  gem 'sass-rails'  gem 'jquery-rails'    gem 'haml'  gem 'figaro'  gem 'bootstrap_form'  gem 'paypal-sdk-adaptivepayments'  gem 'stripe'  gem 'omniauth-stripe-connect'  gem 'appsignal'    group :development, :test do    gem 'byebug',  '9.0.0', platform: :mri  end    group :development do    gem 'web-console',           '3.1.1'    gem 'listen',                '3.0.8'    gem 'spring',                '1.7.2'    gem 'spring-watcher-listen', '2.0.0'  end    group :test do    gem 'rails-controller-testing', '0.1.1'    gem 'minitest-reporters',       '1.1.9'    gem 'guard',                    '2.13.0'    gem 'guard-minitest',           '2.4.4'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

production.rb

 # Devise config    config.action_mailer.default_url_options = { :host => 'd*****.com' }      config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true    config.action_mailer.raise_delivery_errors = false    config.action_mailer.default :charset => "utf-8"      config.action_mailer.smtp_settings = {    address: "smtp.gmail.com",    port: 587,    domain: ENV["GMAIL_DOMAIN"],    authentication: "plain",    enable_starttls_auto: true,    user_name: ENV["GMAIL_USERNAME"],    password: ENV["GMAIL_PASSWORD"]    }  

devise.rb

config.mailer_sender = 'dwo*******@gmail.com'  

application.yml

production:    STRIPE_SECRET_KEY: "sk_live_6yjOP****************"    STRIPE_PUBLISHABLE_KEY: "pk_live_85nZsm****************"    STRIPE_CONNECT_CLIENT_ID: "ca_95VFITa4PgcUn****************"    CONNECTED_STRIPE_ACCOUNT_ID: "acct_18kh****************"    GMAIL_DOMAIN: "gmail.com"    GMAIL_USERNAME: "d********@gmail.com"    GMAIL_PASSWORD: "****************"  

heroku logs

2016-12-03T23:57:40.189178+00:00 app[web.1]: I, [2016-12-03T23:57:40.189101 #4]  INFO -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b]   Rendering devise/mailer/reset_password_instructions.html.erb  2016-12-03T23:57:40.190121+00:00 app[web.1]: I, [2016-12-03T23:57:40.190063 #4]  INFO -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b]   Rendered devise/mailer/reset_password_instructions.html.erb (0.8ms)  2016-12-03T23:57:40.314034+00:00 app[web.1]: D, [2016-12-03T23:57:40.313920 #4] DEBUG -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b] Devise::Mailer#reset_password_instructions: processed outbound mail in 130.1ms  2016-12-03T23:57:40.486943+00:00 app[web.1]: I, [2016-12-03T23:57:40.486840 #4]  INFO -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b] Sent mail to d**************@gmail.com (172.7ms)  2016-12-03T23:57:40.487001+00:00 app[web.1]: D, [2016-12-03T23:57:40.486935 #4] DEBUG -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b] Date: Sat, 03 Dec 2016 23:57:40 +0000  2016-12-03T23:57:40.487003+00:00 app[web.1]: From: d**************@gmail.com  2016-12-03T23:57:40.487003+00:00 app[web.1]: Reply-To: d**************@gmail.com  2016-12-03T23:57:40.487004+00:00 app[web.1]: To: dwo**********@gmail.com  2016-12-03T23:57:40.487005+00:00 app[web.1]: Message-ID: <58435bf44d8ed_43fcedcb1be2c98860@bddbaa93-132b-48e8-9748-833df42451fc.mail>  2016-12-03T23:57:40.487006+00:00 app[web.1]: Subject: Reset password instructions  2016-12-03T23:57:40.487007+00:00 app[web.1]: Mime-Version: 1.0  2016-12-03T23:57:40.487008+00:00 app[web.1]: Content-Type: text/html;  2016-12-03T23:57:40.487008+00:00 app[web.1]:  charset=UTF-8  2016-12-03T23:57:40.487010+00:00 app[web.1]: <p>Hello d**************@gmail.com!</p>  2016-12-03T23:57:40.487009+00:00 app[web.1]: Content-Transfer-Encoding: 7bit  2016-12-03T23:57:40.487009+00:00 app[web.1]:  2016-12-03T23:57:40.487012+00:00 app[web.1]: <p>Someone has requested a link to change your password. You can do this through the link below.</p>  2016-12-03T23:57:40.487012+00:00 app[web.1]:  2016-12-03T23:57:40.487011+00:00 app[web.1]:  2016-12-03T23:57:40.487013+00:00 app[web.1]: <p><a href="https://d**************.com/users/password/edit?reset_password_token=8Ash**************">Change my password</a></p>  2016-12-03T23:57:40.487014+00:00 app[web.1]: <p>If you didn't request this, please ignore this email.</p>  2016-12-03T23:57:40.487013+00:00 app[web.1]:  2016-12-03T23:57:40.487015+00:00 app[web.1]: <p>Your password won't change until you access the link above and create a new one.</p>  2016-12-03T23:57:40.487016+00:00 app[web.1]:  2016-12-03T23:57:40.490471+00:00 app[web.1]: I, [2016-12-03T23:57:40.490413 #4]  INFO -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b] Redirected to https://www.**************.com/users/sign_in  2016-12-03T23:57:40.490700+00:00 app[web.1]: I, [2016-12-03T23:57:40.490635 #4]  INFO -- : [1b1fec5e-5916-4f73-8d8e-829d08fbad0b] Completed 302 Found in 537ms (ActiveRecord: 7.8ms)  

I registered my env variables on heroku and double checked they were correct in the dashboard.

No clue why I am not receiving the e-mails. Heroku logs isn't pointing me anywhere to why its not working. Anyone have any ideas whats wrong with my code? Thank you!!!

How to manage slightly different versions of the same application on Ruby on Rails?

Posted: 03 Dec 2016 10:22 PM PST

I have a Rails 4.2 application that is tailor-made for a specific industry and now I have to upload the same app, but for a new client from a different industry. Given this, I need to do some slightly changes in the database and code (90% of the code should remain the same). What is the best approach to have different versions of the same app? Should I use Rails plugins? I don't want to have two completely separate application because I will be doing maintenance twice almost all the time and having one big app will make it too complicated (and also I need two different database structures)

Please let me know what is the best option.

Thanks!

1 comment:

  1. Custom Controller Method, Route, And Erb >>>>> Download Now

    >>>>> Download Full

    Custom Controller Method, Route, And Erb >>>>> Download LINK

    >>>>> Download Now

    Custom Controller Method, Route, And Erb >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete