Wednesday, October 12, 2016

Ruby on Rails - Difference between redirect_to 'index' and redirect_to objects_path & redirect_to action: 'index' | Fixed issues

Ruby on Rails - Difference between redirect_to 'index' and redirect_to objects_path & redirect_to action: 'index' | Fixed issues


Ruby on Rails - Difference between redirect_to 'index' and redirect_to objects_path & redirect_to action: 'index'

Posted: 12 Oct 2016 07:36 AM PDT

I have a simple model and controller. Let's use Kiwis as an example:

def index      @kiwis = Kiwi.all  end    def destroy      kiwi = Kiwi.find(params[:id])      kiwi.destroy      redirect_to 'index'  end  

I use a delete link on the index page. When I use redirect_to 'index' the page does not refresh the model. I have to do a hard refresh on the page in order for the Kiwi to get removed. However, if I use either redirect_to action: 'index' or redirect_to kiwis_path the page will update after the destroy action. I can't seem to find an explanation on this. Can anyone shed some light on the issue.

Find a record with all associations having a certain value

Posted: 12 Oct 2016 07:39 AM PDT

This is more an SQL question, but I try to solve this in Rails:

I have an User who has_many :days. Days have a status which can be available or booked. I want to find all users who have only available days. I use:

User.includes(:days).where.not(days: { status: 'booked' }).references(:days)  

The generated SQL query looks like this:

SELECT * FROM "users" LEFT OUTER JOIN "days" ON "days"."user_id" = "users"."id" WHERE ("days"."status" != 'booked')  

The results contain users which have both kind of statuses. Thanks for any idea how to solve this!

rails routing, add path name also keep old urls working

Posted: 12 Oct 2016 07:40 AM PDT

in my routes file, when i change

resources :foobar  

to

resources :foobars, path: "foo-bars"  

the urls become example.com/foo-bars, example.com/foo-bars/1 etc. this is ok.

but how can i also keep the old urls, example.com/foobars, example.com/foobar/3 also working?

i know, i can hardcode it,

get "foobars", to: foobar#index  get "foobar/:id", to: foobar#show  ...     

but is there a clean way to implement this?

Return how much data grouped by in Rails

Posted: 12 Oct 2016 07:45 AM PDT

I have the following Ruby code which groups JSON data into months:

  data = data.group_by { |d| d['Date'].to_date.strftime('%Y-%m') }               .collect { |k, v| {Date: k, Total: v.sum { |d| d['Total'].to_i }} }  

So for example it will change:

{"Date":"2012-04-01 12:00:00","Total":"100"},{"Date":"2012-04-02 06:00:00","Total":"200"}  

Into:

{"Date":"2012-04","Total":"300"}  

But I'd like to know how many days were grouped into the new JSON.

So again in my above example, I'd want to return:

{"Date":"2012-04","Total":"300","Days":"2"}  

Why won't Elasticsearch sort my records in descending order?

Posted: 12 Oct 2016 07:15 AM PDT

I have a an index containing documents with a purchased_at. Its mapping is:

"purchased_at" : {    "format" : "strict_date_optional_time||epoch_millis",    "type" : "date"  }  

Documents contain field values in this format: "2013-06-21T11:07:07.000Z". The docs say about sorting:

The _score is not calculated, because it is not being used for sorting.

This is a pretty good indicator if my sort parameter is used or not. I'm using the elasticsearch gem in version 2.0.0. What's working is sorting in ascending order:

MyModel.search("original_id:#{uniq_original_id}", sort: 'purchased_at')  

What doesn't work:

# syntax documented here:  # https://github.com/elastic/elasticsearch-rails/blob/15761247f3e99654bda946a178e50b5365414b59/elasticsearch-model/test/integration/active_record_pagination_test.rb#L106  MyModel.search("original_id:#{uniq_original_id}", sort: [{purchased_at: 'desc'}])    # syntax used here:  # https://github.com/elastic/elasticsearch-rails/blob/15761247f3e99654bda946a178e50b5365414b59/elasticsearch-persistence/examples/notes/application.rb#L114  MyModel.search("original_id:#{uniq_original_id}", sort: [{purchased_at: {order: 'desc'}}])    # syntax used here:  # https://github.com/elastic/elasticsearch-rails/blob/15761247f3e99654bda946a178e50b5365414b59/elasticsearch-rails/lib/rails/templates/searchable.rb#L132  MyModel.search("original_id:#{uniq_original_id}", sort: {purchased_at: 'desc'})  

Needless to say, I'm confused. How can I sort the field in descending order?

Application.css not updating in production with heroku

Posted: 12 Oct 2016 07:23 AM PDT

My application.css is not changing when I push to heroku.

rake assets:precompile # does some things  git add-commit -m "..."  git push heroku master  

Application.css:

*  *= require foundation_and_overrides  * required other files  */    body {   background: red  }  

Production env:

config.assets.compile = true  config.assets.digest = true  

Nothing works, my background is white even if it's set to red. How does the pipeline works with heroku and rails 5, please?

How to parse dynamic content with nokogiri? [duplicate]

Posted: 12 Oct 2016 07:25 AM PDT

This question already has an answer here:

I'm using Nokogiri to parse this site

doc = Nokogiri::HTML(open('https://data.cityofgainesville.org/Governance/311-Service-Requests/78uv-94ar'))  

The problem is that the site has a delay of a few seconds before it returns a list and table update data so the URL I input to Nokogiri to parse is empty of relevant content when Nokogiri retrieves it.

Any ideas of how to retrieve the HTML with a slight delay or any other way?

I think he is looking for the data rather than just the page , The data is loaded through a javascript call

which is a POST request to https://data.cityofgainesville.org/views/INLINE/rows.json?accessType=WEBSITE&method=getByIds&asHashes=true&start=0&length=50

with payload:

{"id":"78uv-94ar","name":"311 Service Requests","attribution":"City of Gainesville - Administrative Services","attributionLink":"http://www.cityofgainesville.org/openGNV/311GNV.aspx","category":"Governance","description":"Non-emergency requests like pothole repairs or damaged street signs can be reported through the 311GNV app (https://play.google.com/store/apps/details?id=com.seeclickfix.gnv311.app&hl=en) or online (http://www.cityofgainesville.org/openGNV/311GNV.aspx).","displayType":"table","licenseId":"PUBLIC_DOMAIN","publicationAppendEnabled":true,"columns":[{"id":253469998,"name":"Id","fieldName":"id","position":1,"description":"The unique identification number for each open service request","width":124,"dataTypeName":"text","tableColumnId":35881929,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469528,"name":"Status","fieldName":"status","position":3,"description":"Status of the request. \nOPEN:  The request has been sent\nACKNOWLEDGED: Staff has acknowledged that the request has been opened.\nCLOSED: The service request has either been made into a work order to fix the problem or the request has been resolved with the requester. \nREOPENED: The request has been reopened by the requester for further investigation","width":172,"dataTypeName":"text","tableColumnId":35881931,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469529,"name":"Summary","fieldName":"summary","position":4,"description":"Brief summary of the service request","width":184,"dataTypeName":"text","tableColumnId":35881932,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469530,"name":"Description","fieldName":"description","position":5,"description":"Detailed description of the service request","width":232,"dataTypeName":"text","tableColumnId":35881933,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469531,"name":"Created","fieldName":"created","position":6,"description":"The date and time the service request was made","width":184,"dataTypeName":"calendar_date","tableColumnId":35881934,"format":{"view":"date_monthdy_shorttime","align":"left"},"flags":null,"metadata":{}},{"id":253469532,"name":"Last updated","fieldName":"last_updated","position":7,"description":"The date and time of the last update made to the service request","width":156,"dataTypeName":"calendar_date","tableColumnId":35881935,"format":{"view":"date_monthdy_shorttime","align":"left"},"flags":null,"metadata":{}},{"id":253469533,"name":"Acknowledged","fieldName":"acknowledged","position":8,"description":"The date and time of when the service request was acknowledged by staff through the online 311 system","width":151,"dataTypeName":"calendar_date","tableColumnId":35881936,"format":{"view":"date_monthdy_shorttime","align":"left"},"flags":null,"metadata":{}},{"id":253469534,"name":"Reopened","fieldName":"reopened","position":9,"description":"The date and time of when the service request was reopened by the requester ","width":146,"dataTypeName":"calendar_date","tableColumnId":35881937,"format":{"view":"date_monthdy_shorttime","align":"left"},"flags":null,"metadata":{}},{"id":253469535,"name":"Closed","fieldName":"closed","position":10,"description":"The date and time of when the service request was \"closed\" by staff. This reflects whether the request was moved into a work order to solve the issue or if the ticket was resolved with the requester","width":149,"dataTypeName":"calendar_date","tableColumnId":35881938,"format":{"view":"date_monthdy_shorttime","align":"left"},"flags":null,"metadata":{}},{"id":253469536,"name":"Minutes to acknowledge","fieldName":"minutes_to_acknowledge","position":11,"description":"The amount of time (in minutes) to acknowledge the open request with a message through the online 311 system","width":141,"dataTypeName":"number","tableColumnId":35881940,"format":{"precisionStyle":"standard","noCommas":"false","align":"right"},"flags":null,"metadata":{}},{"id":253469537,"name":"Minutes to close","fieldName":"minutes_to_close","position":12,"description":"The amount of time (in minutes) to resolve the  request with a message through the online 311 system","width":124,"dataTypeName":"number","tableColumnId":35881941,"format":{"precisionStyle":"standard","noCommas":"false","align":"right"},"flags":null,"metadata":{}},{"id":253469538,"name":"Reported using mobile?","fieldName":"reported_using_mobile","position":13,"description":"If the issue was reported through a mobile device","width":216,"dataTypeName":"text","tableColumnId":35881939,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469539,"name":"Assignee name","fieldName":"assignee_name","position":14,"description":"The department or office the request has been assigned to","width":256,"dataTypeName":"text","tableColumnId":35881942,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469540,"name":"Address","fieldName":"location_detail","position":15,"description":"The address of the issue (manually input by the requester)","width":280,"dataTypeName":"text","tableColumnId":35881943,"format":{"displayStyle":"plain","align":"left"},"flags":null,"metadata":{}},{"id":253469541,"name":"Location","fieldName":"location","position":16,"description":"The location of the issue in latitude and longitude (used to place points on a map)","width":196,"dataTypeName":"location","tableColumnId":35881944,"format":{"view":"coords","rdf":"","align":"left"},"flags":null,"metadata":{}}],"metadata":{"renderTypeConfig":{"visible":{"table":true}},"rowLabel":"Row","availableDisplayTypes":["table","fatrow","page"],"jsonQuery":{"order":[{"ascending":true,"columnFieldName":"id"}]}},"query":{"orderBys":[{"ascending":true,"expression":{"columnId":253469998,"type":"column"}}]},"tags":["311","request","citizen","repair","non-emergency","reports"],"flags":["default","restorable","restorePossibleForType"],"originalViewId":"78uv-94ar","displayFormat":{}}

Ruby on Rails method declared in model isn't accessible from link_to

Posted: 12 Oct 2016 07:22 AM PDT

so I have 2 methods in one of my models. The model name is user.rb, and the class is User. Here are the methods I declared

  def follow(user_id)       following_relationships.create(following_id: user_id)    end      def unfollow(user_id)       following_relationships.find_by(following_id: user_id).destroy    end  

And in my view I have a link_to that method like this:

= link_to 'Following', unfollow_user_path, remote: true  

It is HAML but that shouldn't make a difference. When I start the server and try to go to someone's page I get this error:

undefined local variable or method `unfollow_user_path' for #<#:0x00563935a456e0>

This shouldn't be happening because I declared the method in the user model.

Any help would be appreciated, thank you.

How to search a collection of SitePrism sections for a section matching a specific criterion

Posted: 12 Oct 2016 06:42 AM PDT

I have defined a sections element as containing a list of individual elements to model a data table. Each Section of the Sections collection corresponds to a row of the table and each element of the Sections definition corresponds to a column of the row.

I want to search the Sections collection for a Section which corresponds to the row with a given id and then click on an element of that row.

Unfortunately I cant find a way of searching the array of Section objects returned by PageObjectClass.<sections_name>.

If instead I define the set of rows as elements then PageObjectClass.<elements_name> returns a set of Capybara elements that I can do a Capybara find on but then I can't use the SitePrism section.element syntax.

Using the elements.find syntax seems to have a code smell because thus far the CSS for accessing elements has been abstracted away in the PageObject class definition - now I have to refer to the CSS for a specific element in the test code in order to click on it.

What am I missing here? How come there are so few examples of the use of data tables in SitePrism online discussion and why haven't more people hit this problem?

The only reference that I did hit upon is https://github.com/natritmeyer/site_prism/issues/91

Did anything ever come of this suggestion?

Active model Serializers does not work when i try to return a hash of multiple models via Rails?

Posted: 12 Oct 2016 06:53 AM PDT

I am working on Rails 5 api only app.

So this is my model serializer

class MovieSerializer < ActiveModel::Serializer    attributes :id ,:name,:release_year,:story,:in_theater,:poster,:score,:user_count      belongs_to :age_rating    belongs_to :company    has_many :category , through: :movie_category    end    class CelebritySerializer < ActiveModel::Serializer    attributes :id, :first_name, :last_name      has_many :movie_celebrity    end    class MovieCelebritySerializer < ActiveModel::Serializer    attributes :id,:vacancy,:title      belongs_to :movie    belongs_to :celebrity    end  

This is my controller

class Api::V1::MoviesController < ApplicationController      # GET /v1/movies/:id    def show        movie = Movie.find_by(id: params[:id])      casts = MovieCelebrity.where(movie_id: params[:id],vacancy: "cast")      directors = MovieCelebrity.where(movie_id: params[:id],vacancy: "director")        render :json => {:movie => movie, :casts => casts , :directors => directors}    end    end  

So this is what i got when i made a request

{    "movie": {      "id": 1,      "name": "0 The Doors of Perception",      "release_year": 2007,      "story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",      "in_theater": false,      "age_rating_id": 2,      "company_id": 5,      "created_at": "2016-10-12T12:45:26.213Z",      "updated_at": "2016-10-12T12:45:26.213Z",      "release_date": "2016-01-18",      "poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",      "score": 0,      "user_count": 6950    },    "casts": [      {        "id": 2,        "vacancy": "cast",        "title": "Pro x",        "movie_id": 1,        "celebrity_id": 56,        "created_at": "2016-10-12T12:45:28.001Z",        "updated_at": "2016-10-12T12:45:28.001Z"      },      {        "id": 3,        "vacancy": "cast",        "title": "Magneto",        "movie_id": 1,        "celebrity_id": 23,        "created_at": "2016-10-12T12:45:28.006Z",        "updated_at": "2016-10-12T12:45:28.006Z"      }    ],    "directors": [      {        "id": 1,        "vacancy": "director",        "title": "",        "movie_id": 1,        "celebrity_id": 17,        "created_at": "2016-10-12T12:45:27.993Z",        "updated_at": "2016-10-12T12:45:27.993Z"      }    ]  }  

It seems like Active model serializer did not work. Because if i only return one object it worked fine like this.

def show        movie = Movie.find_by(id: params[:id])      casts = MovieCelebrity.where(movie_id: params[:id],vacancy: "cast")      directors = MovieCelebrity.where(movie_id: params[:id],vacancy: "director")        #render :json => { :movie => movie, :casts => casts , :directors => directors }      render :json => movie    end        {    "id": 1,    "name": "0 The Doors of Perception",    "release_year": 2007,    "story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",    "in_theater": false,    "poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",    "score": 0,    "user_count": 6950,    "age_rating": {      "id": 2,      "name": "PG"    },    "company": {      "id": 5,      "name": "Gislason, Jacobs and Graham"    },    "category": [      {        "id": 4,        "name": "Biography"      },      {        "id": 16,        "name": "Mystery"      }    ]  }  

How can i fixed this and make the Active model serializer works fine with multiple models hash object?

Thanks!

Rails 5 left outer join using includes() and where()

Posted: 12 Oct 2016 07:46 AM PDT

I'm having a heck of a time getting the intended behavior using includes() and where().

Result I want:
- All students (even if they have zero check-ins)
- All check-ins in the Library

Result I'm getting:
- Only students with check-ins in the library
- All check-ins in the library, for those students


Currently my code is based off of this: http://edgeguides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations

Which describes the behavior I want:

Article.includes(:comments).where(comments: { visible: true })  

If, in the case of this includes query, there were no comments for any articles, all the articles would still be loaded.

My code:

@students = Student.includes(:check_ins)                      .where(check_ins: {location: "Library"})                      .references(:check_ins)  

.

class CheckIn < ApplicationRecord    belongs_to :student  end  

.

class Student < ApplicationRecord    has_many :check_ins, dependent: :destroy  end  

The generated SQL query:

SELECT "students"."id" AS t0_r0,"check_ins"."id" AS t1_r0, "check_ins"."location" AS t1_r1, "check_ins"."student_id" AS t1_r6 FROM "students" LEFT OUTER JOIN "check_ins" ON "check_ins"."student_id" = "students"."id" WHERE "check_ins"."location" IN ('Library')  

This SQL query gives the join behavior I want:

SELECT first_name, C.id FROM students S LEFT OUTER JOIN check_ins C ON C.student_id = S.id AND location IN ('Library');  

Devise Sign Up Freeze

Posted: 12 Oct 2016 07:01 AM PDT

I am getting a strange error with Devise on my Ruby on Rails app. When proceeding to the default Sign-Up form, after entering the email, and password field and then pressing sign-up, the button becomes unclickable and then nothing happens.

Previous Users have been successfully registered via this method, so I can confirm it did work previously. I have since not registered any new users in many months.

Heroku logs don't show any activity except for getting the sign-up page.

Sign Up Image

2016-10-12T13:34:23.799746+00:00 app[web.1]: Started GET "/users/sign_up" for 101.164.74.67 at 2016-10-13 00:34:23 +1100 2016-10-12T13:34:23.801698+00:00 app[web.1]: Processing by Users::RegistrationsController#new as HTML 2016-10-12T13:34:23.806692+00:00 app[web.1]: Rendered devise/_basic_form.html.erb (2.8ms) 2016-10-12T13:34:23.807344+00:00 app[web.1]: Rendered devise/shared/_links.html.erb (0.5ms) 2016-10-12T13:34:23.807443+00:00 app[web.1]: Rendered devise/registrations/new.html.erb within layouts/application (3.8ms) 2016-10-12T13:34:23.810189+00:00 app[web.1]: Completed 200 OK in 8ms (Views: 7.0ms | ActiveRecord: 0.0ms) 2016-10-12T13:34:24.055291+00:00 heroku[router]: at=info method=GET path="/assets/application-fca53857b919fcfd74765023315d07a5dcd04e0903cc840513af7edff1a08efd.css" host=www.puntsquad.com request_id=aa91286f-b fd8-4650-bc12-d6d9e51da3a9 fwd="101.164.74.67" dyno=web.1 connect=1ms service=3ms status=304 bytes=133

2016-10-12T13:34:24.074652+00:00 heroku[router]: at=info method=GET path="/assets/chartkick-f077bcf66f815b88f8d0c98ee47a985e34e82baad8e59cd59bf539b48610e20d.js" host=www.puntsquad.com request_id=99ee8e9f-c1e6 -446b-97d9-890d25675a3f fwd="101.164.74.67" dyno=web.1 connect=1ms service=4ms status=304 bytes=133 2016-10-12T13:34:24.062979+00:00 heroku[router]: at=info method=GET path="/assets/application-8ca7fdc6c863cd6724872dba3750dc3ad3fc9a9ea1921a4fac1e31356e0df7ba.js" host=www.puntsquad.com request_id=89d93555-31 c4-4276-9697-62a802a8faf5 fwd="101.164.74.67" dyno=web.1 connect=1ms service=3ms status=304 bytes=133 2016-10-12T13:34:24.310851+00:00 heroku[router]: at=info method=GET path="/assets/logo-dark-text-25488e5bdfd754d5a6323b07d20d3ad45a14d4914d89fb6b079fd26a90def0a9.png" host=www.puntsquad.com request_id=21a3ebe e-c828-4469-b64c-c1e78dcefeb9 fwd="101.164.74.67" dyno=web.1 connect=2ms service=5ms status=304 bytes=133 2016-10-12T13:34:24.333208+00:00 heroku[router]: at=info method=GET path="/assets/logo-842bcfb411552d5c9608dd20e5f3824023295525e43950d93b720fbf047eed82.png" host=www.puntsquad.com request_id=81224e9e-ac3b-466 7-a580-01991908c44b fwd="101.164.74.67" dyno=web.1 connect=1ms service=3ms status=304 bytes=133 2016-10-12T13:34:24.343606+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont-ff82aeed6b9bb6701696c84d1b223d2e682eb78c89117a438ce6cfea8c498995.woff2?v=4.5.0" host=www.puntsquad.com req uest_id=8bf04f8a-9f14-4b90-a50a-ffe50666a70d fwd="101.164.74.67" dyno=web.1 connect=2ms service=3ms status=304 bytes=133 2016-10-12T13:34:24.755694+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont-c812ddc9e475d3e65d68a6b3b589ce598a2a5babb7afc55477d59215c4a38a40.woff?v=4.5.0" host=www.puntsquad.com requ est_id=ac598fcc-b038-45ca-a78c-6557dc96a897 fwd="101.164.74.67" dyno=web.1 connect=1ms service=9ms status=304 bytes=133 2016-10-12T13:34:24.995528+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont-7b5a4320fba0d4c8f79327645b4b9cc875a2ec617a557e849b813918eb733499.ttf?v=4.5.0" host=www.puntsquad.com reque st_id=6d8e4172-8b95-4615-8479-0e9bd83cef17 fwd="101.164.74.67" dyno=web.1 connect=1ms service=6ms status=304 bytes=133 2016-10-12T13:34:25.261030+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=www.puntsquad.com request_id=c2e6c575-4e49-4b09-91eb-001ea0d21bbb fwd="101.164.74.67" dyno=web.1 connect=1ms servic e=9ms status=200 bytes=228

Rails similar form fields across multiple views

Posted: 12 Oct 2016 06:40 AM PDT

This question expands on my earlier question posted Rails combining RESTful methods in a new controller. With my rails web app, a user registers and creates a project. For conversion tracking, I am creating a getting_started view that will allow people to register and create a project in a single action (on a single page).

I have the issue now that especially for the projects, I will have form fields sitting on two views, namely the project partial _form that renders on the new, and update views. And secondly a form for the user and project details on the getting_started view. I feel like I'm duplicating a lot of code, and rails has a simpler way I'm just not seeing. I also change the project fields quite regularly and would like a single point to update the form for both the project _form as well as the getting_started _form.

I've read that partial views, in partial views can hinder performance, and I also don't think you can simply include form fields in a partial, and render them in a form (will throw out an error asking what "f" means I assume?).

Any suggestions how best to do this?

URL changes into dot instead of slash

Posted: 12 Oct 2016 07:17 AM PDT

I am building an reservation system therefore a user can view their trips. A reservation belongs_to a room and a room has_may reservations so @room is a foreign key. I want to link the image of a room to the show room view. However when I click on the link, the URL is changing to c9users.io/rooms.1 instead of c9users.io/rooms/1.

What steps are necessary to make this work?

What is causing this behavior?

It does not look like a pluralization error because I also have tried:

<%= link_to room_path(trip.room) do %>   

Unfortunately the result is the same.

your_trips.html.erb

<% @trips.each do |trip| %>          <%= link_to rooms_path(trip.room) do %>              <div>                  <%= image_tag trip.room.photos[0].image.url(:thumb) if trip.room.photos.length > 0 %>              </div>          <% end %>  <% end %>  

routes.rb

Rails.application.routes.draw do      root 'static_pages#welcome'      devise_for :admin_users, ActiveAdmin::Devise.config    ActiveAdmin.routes(self)    devise_for :users,               :path => '',               :path_names => {:sign_in => 'login', :sign_out => 'logout', :edit => 'profile'},               :controllers => {:omniauth_callbacks => 'omniauth_callbacks'}      get 'rentout' => 'static_pages#rentout'    get 'about' => 'static_pages#about'    get 'impressum' => 'static_pages#impressum'      resources :rooms, only: [:index, :show]    resources :photos      resources :rooms do       resources :reservations, only: [:create]    end      get '/preload' => 'reservations#preload'    get '/preview' => 'reservations#preview'      get '/your_trips' => 'reservations#your_trips'  end  

reservations_controller.rb

class ReservationsController < ApplicationController      before_action :authenticate_user!        def preload          room = Room.find(params[:room_id])          today = Date.today          reservations = room.reservations.where("start_date >= ? OR end_date >= ?", today, today)            render json: reservations      end        def preview          start_date = Date.parse(params[:start_date])          end_date = Date.parse(params[:end_date])            output = {              conflict: is_conflict(start_date, end_date)          }            render json: output      end        def create          @room = Room.find(params[:room_id])          @reservation = current_user.reservations.create(reservation_params.merge(room_id: @room.id))          redirect_to @reservation.room, notice: "Your reservation has been created"      end        def your_trips          @trips = current_user.reservations      end        private          def is_conflict(start_date, end_date)              room = Room.find(params[:room_id])                check = room.reservations.where("? < start_date AND end_date < ?", start_date, end_date)              check.size > 0? true : false          end            def reservation_params              params.require(:reservation).permit(:start_date, :end_date, :price, :total, :room_id)          end  end  

rooms_controller.rb

class RoomsController < ApplicationController    before_action :set_room, only: [:show]      def index      @rooms = Room.all    end      def show      @photos = @room.photos    end      private      def set_room        @room = Room.find(params[:id])      end  end  

I am using Rails 5.0.1 with Cloud9 IDE.

Unable to update the record because of validation of name

Posted: 12 Oct 2016 06:44 AM PDT

namespace :send_query do          task :to_admins => :environment do           contacts = Contact.select(:name, :mobile, :company, :requirement).where(email_sent: false).distinct          if !contacts.blank?              contacts.each do |contact|                  GuestMailer.query_email(contact.name,            contact.mobile,            contact.company,            contact.requirement).deliver            contact.update!(email_sent: true)              end           end          puts "done sending query emails"      end  end  

I wrote a rake task to send emails. After sending email, I am updating the field email_sent to true. But the transaction is rolling back after sending email.

(0.2ms)  BEGIN    Contact Exists (0.7ms)  SELECT  1 AS one FROM "contacts" WHERE "contacts"."name" = $1 AND ("contacts"."id" IS NOT NULL) AND "contacts"."mobile" = $2 AND "contacts"."requirement" = $3 AND "contacts"."company" = $4 LIMIT $5  [["name", "vamsi pavan mahesh"], ["mobile", "9247474925"], ["requirement", "yo yo honey singhu"], ["company", "mahesh@bla.com"], ["LIMIT", 1]]     (0.2ms)  ROLLBACK  rake aborted!  ActiveRecord::RecordInvalid: Validation failed: Name has already been taken  

Here is the Contact model

# == Schema Information  #  # Table name: contacts  #  #  id          :integer          not null, primary key  #  name        :string  #  mobile      :string  #  company     :string  #  requirement :text  #  created_at  :datetime         not null  #  updated_at  :datetime         not null  #  email_sent  :boolean          default(FALSE)  #    class Contact < ApplicationRecord      validates :name, presence: true       validates :mobile, presence: true      validates :requirement, presence: true      validates_uniqueness_of :name, scope: [:mobile, :requirement, :company]  end  

Does anybody know another way to create join table migration and specify a specific name of references columns in join table?

Posted: 12 Oct 2016 07:44 AM PDT

I have these two models:

 module Studying    class Student < ApplicationRecord     has_and_belongs_to_many :instructors,                          class_name: 'Studying::Instructor',                          foreign_key: 'studying_student_id',                          association_foreign_key: 'studying_instructor_id'    end  end       module Studying    class Instructor < ApplicationRecord     has_and_belongs_to_many :students,                          class_name: 'Studying::Student',                          foreign_key: 'studying_instructor_id',                          association_foreign_key: 'studying_student_id'    end  end  

And for join_table I have generated migration:

def change    create_table :studying_instructors_students, id: false do |t|    t.belongs_to :studying_instructor, index: { name: 'index_instructors_students_on_studying_instructor_id' }    t.belongs_to :studying_student, index: { name: 'index_instructors_students_on_studying_student_id' }    end  end  

So all is working fine, but the point is, that my senior comrade tells me that I should not use in models things such as:

  foreign_key:  'studying_instructor_id',  

and

  association_foreign_key: 'studying_student_id'    

but instead of these I should use:

  foreign_key:  'instructor_id',   

and

  association_foreign_key: 'student_id'  

and in the same way in the first model because this is against the convention. I do not know how I can do this in this models and in tables (how you already understand tables names in db: studying_instructors and studying_students).

Any advice please ?

Rails routes vs Angular2 routes

Posted: 12 Oct 2016 06:03 AM PDT

I'm using Anular2 inside a rails application. My entry point is my index.html that is located in my public folder. What I need is to call this index.html with an id (representing the entity that called it) like this index/id=2. But whenever I issue such a call, I got an error, because my rails application first intercepts the call and try to resolve this route which of course doesn't exist on my rails route. Is there a way to solve this issue, or should I move my index under a rails view ?

Do I need two different applications on Spotify Developer site for an iOS and web client of the same app?

Posted: 12 Oct 2016 06:02 AM PDT

Might be answering my own question, but do the apps need different client secrets and different callbacks. And if they do, how do I configure it on Spotify?

t.time saving field as a string in ActiveRecord

Posted: 12 Oct 2016 07:15 AM PDT

I have a table with a field called time_start. Example:

t.time :time_start  

When I try to save the attribute, it saves it as a Hash-String. Example:

params{         "time_start(1i)"=>"2016",         "time_start(2i)"=>"10",         "time_start(3i)"=>"12",         "time_start(4i)"=>"23",         "time_start(5i)"=>"59",  }    => "{1=>2016, 2=>10, 3=>12, 4=>23, 5=>59}"  

I cannot figure out why the attribute is saving a string instead of parsing into a Time obj. I have even tried a rake db:rollback VERSION=123456546 to the migration just before it, but it still saves the value as a string after the rake db:migrate. I am not allowed to drop the table.

Force stylesheet_link_tag to locate hashed asset in Rails 4

Posted: 12 Oct 2016 05:55 AM PDT

We're coming off of using the asset_sync gem for managing our assets. I'm trying to setup the Asset Pipeline using these settings.

development.rb

  config.assets.debug = true    config.assets.compile = false    config.assets.digest = true    config.cache_classes = true    config.eager_load = false  

application.rb

  config.assets.enabled = true    config.assets.css_compressor = :sass    config.assets.js_compressor = :uglifier    config.assets.version = '1.1'  

I'm precompiling in Development and the assets are going into the public directory (hashed asset for each file). When using the stylesheet_link_tag, it works perfectly if I refer to the hashed asset directly:

stylesheet_link_tag("/assets/branding/visit/skin-295511b052d49d541763f276ddcf4efc.css")  

But I need to be able to just call skin.css and be served the correct hashed skin.css file. I currently get a 404 with this:

stylesheet_link_tag("/assets/branding/visit/skin.css")  

Is there a setting I'm missing to point to the hashed asset? Thanks for any advice.

Tech Specs

Ruby: 2.3.1

Rails: 4.2.7.1

how to remove a second AMPERSAND in a string?

Posted: 12 Oct 2016 06:54 AM PDT

1.how to remove second AMPERSAND from following string? "apple&banana&grape&apple"

2.how to split the string at second AMPERSAND for following string? I want to ignore the first AMPERSAND and split from second AMPERSAND onwards. "apple&banana&grape&apple"

How do I import react-typeahead to another js file with Rails assets

Posted: 12 Oct 2016 07:34 AM PDT

I have Rails 5 project and I'm using default Rails asset pipeline. I'm using rails-react to for implementing React components to my views.

Gemfile

gem 'react-rails', '~> 1.0'  source 'https://rails-assets.org' do    gem 'rails-assets-react-typeahead'  end  

application.js

//= require jquery  //= require jquery_ujs  //= require bootstrap-sprockets  //= require react  //= require react-typeahead  //= require components  //= require turbolinks  //= require react_ujs  

I would like to use react-typeahead which has Typeahead and TypeaheadTokenizer React elements already implement. Problem is that I would then need somehow import the react-typehead variables to my react components so that I could use them.

The react-typehead documentation shows only example for node.js how to require the Typeahead function to another file.

var Typeahead = require('react-typeahead').Typeahead;  

Can this be somehow implemented with Rails assets pipeline so that I'm able to "require" the Typeahead to my React component files when I need a Typeahead input field for my form. I have written my components with javascript (jsx) but I could transform them to ES6 if that provides a way to import variable from another file. RequireJS migh offer a solution for this, but it would then mean that I would need to move away from Rails asset pipeline If I understood correctly. I'm trying to find a solution that I can use with asset pipeline.

The error that I'm getting is quite simple, "Uncaught ReferenceError: Typeahead is not defined"

Edit: added application.js

How do I get to calling a method from dependencies.rb after calling a method from a gem?

Posted: 12 Oct 2016 05:32 AM PDT

In order to find out more about how Ransack (a Gem) works I started debugging it, which brings me to the console with this prompt:

   28:   def index     29:     debugger  => 30:     @search = ControlCenter.ransack(params[:q])  

I wanna go deeper, so I type

(byebug) step  

which gives me this output:

[197, 206] in /Users/xx/.rvm/gems/ruby-2.3.0@xxx/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb       201:       def const_missing(const_name)  => 202:         from_mod = anonymous? ? guess_for_anonymous(const_name) : self     203:         Dependencies.load_missing_constant(from_mod, const_name)     204:       end  

Looking at the ransack method:

def ransack(params = {}, options = {})    Search.new(self, params, options)  end  

I just can't make sense of what's going on here. Aren't there calls in between? How am I ending up with ActiveSupport::Dependencies? Am I not following every call with step?

Filter on an array of ruby objects

Posted: 12 Oct 2016 06:28 AM PDT

I'm writing a process in ruby to calculate top statistics. I have a question on how to filter an object array.

Given the following object array, This is sorted by brokerage, avg_price and avg_rating.

data = [  {name: "something1", brokerage: "some broker1", avg_price: 100, avg_rating: 1},  {name: "something2", brokerage: "some broker1", avg_price: 90, avg_rating: 2},  {name: "something3", brokerage: "some broker1", avg_price: 80, avg_rating: 3},  {name: "something4", brokerage: "some broker2", avg_price: 100, avg_rating: 1},  {name: "something5", brokerage: "some broker2", avg_price: 90, avg_rating: 2},  {name: "something6", brokerage: "some broker2", avg_price: 80, avg_rating: 3},  {name: "something7", brokerage: "some broker3", avg_price: 100, avg_rating: 1},  {name: "something8", brokerage: "some broker3", avg_price: 90, avg_rating: 2},  {name: "something9", brokerage: "some broker3", avg_price: 80, avg_rating: 3},  {name: "something10", brokerage: "some broker4", avg_price: 100, avg_rating: 1}]  

Is there any map, collect, select etc function that will allow me to reduce this array to:

[{:name=>"something1", :brokerage=>"some broker1", :avg_price=>100, :avg_rating=>1},   {:name=>"something4", :brokerage=>"some broker2", :avg_price=>100, :avg_rating=>1},   {:name=>"something7", :brokerage=>"some broker3", :avg_price=>100, :avg_rating=>1},   {:name=>"something10", :brokerage=>"some broker4", :avg_price=>100, :avg_rating=>1}]  

The latter gives me the top broker in each brokerage. I know that this is doable using an each block and simply writing out the first instance of a new brokerage. I'm just wondering if ruby has a built in function for this.

Identify how many listeners are currently existing for a pubnub client

Posted: 12 Oct 2016 05:02 AM PDT

Is there any way to identify how many listeners are currently existing for a Pubnub client in ruby? And also any method in ruby to delete all listeners existing for a Pubnub client.

ArgumentError in Admin::Sessions#new

Posted: 12 Oct 2016 05:05 AM PDT

My rails app has Ruby versions are

gem 'rails', '4.2.5'  gem 'mysql2', '~> 0.3.18'  

I'm working on ECommerce platform, when i login to admin section, getting this error

ArgumentError in Admin::Sessions#new /home//development//app/views/admin/sessions/new.html.haml where line #1 raised:

wrong number of arguments (given 3, expected 0..1) Extracted source (around line #1):

=form_tag admin_sessions_path(:secure => true), :method => :post, :novalidate => 'novalidate', :id => "signInForm", :class => "aw-form user-form session" do %fieldset %legend.group %span Log In: - if !@session.errors.empty? .failure-notification Please enter valid credentials

My code is at app/views/admin/sessions/new.html.haml

=form_tag admin_sessions_path(:secure => true), :method => :post, :novalidate => 'novalidate', :id => "signInForm", :class => "aw-form user-form session" do  

Help out me to fix this issue

Is there possibity for using two 1x dynos and one 2x dyno in heroku?

Posted: 12 Oct 2016 05:00 AM PDT

Here i deployed one application in heroku. At starting i am using standard 1x dyno . Up to there is no problem but ruuning special feature i am getting problem in traffic. so can i use like this. thanks in advance

Ruby Rspec AXLSX unit testing error

Posted: 12 Oct 2016 04:48 AM PDT

Here is my code.

wb = xlsx_package.workbook  wb.add_worksheet(name: 'my_work_sheet') do |sheet|     sheet.add_row ['first row']  end  

I have written unit test for above code. Here is it:

it 'should write data in file' do      workbook = double('Workbook')      worksheet = double('Worksheet')        expect(xlsx_package).to receive(:workbook).and_return(workbook)      expect(workbook).to receive(:add_worksheet).with(name: 'my_work_sheet').and_return(worksheet)      expect(worksheet).to receive(:add_row).with(['first row'])  end  

I am getting error 'xlsx_package' not found

Rails first or initialize not working

Posted: 12 Oct 2016 05:10 AM PDT

I have a product I have an order. I have a booking in between.

Whenever I make a booking from the product to the order it saves a new unique booking.

It should:

  1. Save a new booking when it's the first made from this product.
  2. Not make a new booking, but find and overwrite an old one, if the product has already been booked once.
  3. If the product has already been booked on the order, but no changes are made, no database transactions are made.
  def create      @order = current_order      @booking = @order.bookings.where(product_id: params[:product_id]).first_or_initialize      product = @booking.product      if @booking.new_record?        @booking.product_name = product.name        @booking.product_price = product.price      else      @booking.product_quantity = params[:product_quantity]      @booking.save      @order.sum_all_bookings       @order.save    end  

Doesn't work

Rails 4.2 with Kaminari 0.17.0 - how to change "?page=x" to "/x" (ie no query string)

Posted: 12 Oct 2016 07:46 AM PDT

Whilst I understand that Tim Berners Lee specified the use of ? for dynamic url segments, the client on my project doesn't want them.

So does anyone know how, using Kaminari for paging, I can change the routing to replace:

domain.com/searchresults?page=x  

with

domain.com/searchresults/x  

Obviously, this has to work when you click next page, prev page etc so that the url always changes x to the correct page number.

No comments:

Post a Comment