I am using bootstrap and I have a link that redirects to images#show action from home#index. The link is written in haml:
- url = #entry.class.to_s.downcase.singularize
= link_to(send("#{url}_path", #entry), data: { 'type' => #entry.class.to_s.downcase }) do
= yield
So currently, the home#index displays a list of images and when an image is clicked on, the link written above redirects the user to the view for the specific image Ex: images/1. That is to say that #entry represents the image and when clicked redirects to the specific image or (#entry).
I do not want to move away from the homepage (home#index), I just want to display a modal view that will take into account which images ( or #entry) was clicked on. How do I modify this link and add code that will display a bootstrap modal when the above link is clicked on ? What other steps should I follow ? I just need help to the point of displaying the modal.
Here is my trace:
Started GET "/images/3" for ::1 at 2016-09-07 22:28:10 -0400
Processing by ImagesController#show as */*
Parameters: {"id"=>"3"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Image Load (0.3ms) SELECT "images".* FROM "images" WHERE "images"."id" = $1 LIMIT 1 [["id", 3]]
Group Load (0.4ms) SELECT DISTINCT "groups".* FROM "groups" INNER JOIN "group_memberships" ON "groups"."id" = "group_memberships"."group_id" WHERE "group_memberships"."member_id" = $1 AND "group_memberships"."member_type" = $2 AND "group_memberships"."group_type" = $3 [["member_id", 1], ["member_type", "User"], ["group_type", "Group"]]
GroupMembership Load (0.4ms) SELECT "group_memberships".* FROM "group_memberships" WHERE "group_memberships"."member_id" = $1 AND "group_memberships"."member_type" = $2 [["member_id", 3], ["member_type", "Image"]]
GroupMembership Load (0.5ms) SELECT "group_memberships".* FROM "group_memberships" WHERE "group_memberships"."group_type" = $1 AND "group_memberships"."member_type" = $2 AND "group_memberships"."member_id" = $3 AND "group_memberships"."group_id" IN (-1, -1) [["group_type", "Group"], ["member_type", "User"], ["member_id", 1]]
Rendered images/_modal.html.erb (0.0ms)
Rendered images/show.js.erb (1.2ms)
Completed 200 OK in 27ms (Views: 10.0ms | ActiveRecord: 1.9ms)
One option is to use a js template and change your links to use use the remote: true option:
<%- #images.each do |image| -%>
<%= link_to '...', image_path(image) remote: true %>
<%- end -%>
<div id="modals"></div>
Next in the controller the response type can be set to js (probably a good idea to also keep the html option around):
respond_to do |format|
format.js
end
Then in the template that handles the js:
// app/views/images/show.js.erb
$("#modals").html('<%= j render "images/modal", image: #image %>');
$('#modals .modal').modal();
$('#modals .modal').modal('.toggle');
Finally add a partial for the modal and setup any markup needed:
<!-- app/views/images/_modal.html.erb -->
<div class="modal fade">
...
<%= image_tag(image.url, class: "img-responsive") %>
...
</div>
Related
Desired output: only the data from events, like:
[{"id":600,"title":600,"start":"2018-10-17T15:24:06.000Z","end":"2018-10-17T17:11:06.000Z","color":"green"}
[{"id":601,"title":601,"start":"2019-10-17T15:24:06.000Z","end":"2018-10-17T17:11:06.000Z","color":"green"}
Current output for some reason also gives info from application.html.erb and from application.js and other files:
events/_event.json.jbuilder:
json.id event.id
json.title event.id
json.start event.starts_at
json.end event.ends_at
json.color event.status_color unless event.status_color.blank?
json.url event_url(event, format: :json)
index.json.jbuilder:
json.array! #events, partial: 'events/event', as: :event
Contoller:
class EventsController < ApplicationController
def index
#events = Event.all
##q = Event.ransack(params[:q])
##events = #q.result.includes(:location, :client, :jobs).paginate(:page => params[:page], :per_page => 15).order("created_at DESC")
end end
Console:
Started GET "/events.json" for 143.27.126.62 at 2019-01-31 10:49:24 +0000
Cannot render console from 143.27.126.62! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by EventsController#index as JSON
User Load (0.8ms) SELECT "users".* FROM "users" WHERE (users.tenant_id IS NULL) AND "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /usr/local/rvm/gems/ruby-2.5.3/bundler/gems/milia-4c36b46f3f42/lib/milia/control.rb:102
Tenant Load (0.7ms) SELECT "tenants".* FROM "tenants" INNER JOIN "tenants_users" ON "tenants"."id" = "tenants_users"."tenant_id" WHERE (tenants.tenant_id IS NULL) AND "tenants_users"."user_id" = $1 [["user_id", 1]]
↳ /usr/local/rvm/gems/ruby-2.5.3/bundler/gems/milia-4c36b46f3f42/lib/milia/control.rb:69
MILIA >>>>> [change tenant] new: 1 old: 1
MILIA >>>>> [auth_tenant callback]
Tenant Load (0.6ms) SELECT "tenants".* FROM "tenants" WHERE (tenants.tenant_id IS NULL) AND "tenants"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /usr/local/rvm/gems/ruby-2.5.3/bundler/gems/milia-4c36b46f3f42/lib/milia/base.rb:126
CACHE Tenant Load (0.0ms) SELECT "tenants".* FROM "tenants" WHERE (tenants.tenant_id IS NULL) AND "tenants"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /usr/local/rvm/gems/ruby-2.5.3/bundler/gems/milia-4c36b46f3f42/lib/milia/base.rb:126
CACHE Tenant Load (0.0ms) SELECT "tenants".* FROM "tenants" WHERE (tenants.tenant_id IS NULL) AND "tenants"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /usr/local/rvm/gems/ruby-2.5.3/bundler/gems/milia-4c36b46f3f42/lib/milia/base.rb:126
Rendering events/index.json.jbuilder within layouts/application
Event Load (80.7ms) SELECT "events".* FROM "events" WHERE (events.tenant_id = 1)
↳ app/views/events/index.json.jbuilder:1
Rendered events/_event.json.jbuilder (1.1ms)
Rendered events/_event.json.jbuilder (0.3ms)
Rendered events/_event.json.jbuilder (0.2ms)
Rendered events/_event.json.jbuilder (0.2ms)
Rendered events/_event.json.jbuilder (0.3ms)
Maybe it has to do with Rendering events/index.json.jbuilder within layouts/application?
Because I need to write some code, I'm posting this now as an answer:
Are you sure it's doing a /events.json? or it is doing a /events instead? (looking at your screenshot, I think you just typed in /events.json there in the Chrome address bar, because it should include the "hostname" there by default (from AFAIK).
How rails determine what the response format to render is through this doc:
Example:
GET /posts/5.xml | request.format => Mime::XML
GET /posts/5.xhtml | request.format => Mime::HTML
GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first`
Therefore,
GET /events.xml will by "default" render app/views/events.xml.TEMPLATE_ENGINE
GET /events.json will by "default" render app/views/events.json.TEMPLATE_ENGINE
GET /events will by "default" infer from the first value in the "Accept" header. i.e. if I type in this URL in Chrome address bar, looking at Chrome Network tab, Chrome seems to generate the "Accept" header as follows:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
...of which the first value is text/html, and is why Rails by "default" will render app/views/posts.html.TEMPLATE_ENGINE.
^ this is currently my guess why you are seeing an HTML instead, because probably the request you are doing is GET /events instead of the correct one which is GET /events.json. You can still however do GET /events, but you need to modify the "Accept" header to equal to "application/json"
Debugging:
To test my theory above, can you open Chrome "Network Tab" (click HERE if you don't know how to open it). And then do / send a request as normal to your Rails endpoint (dunno maybe you were clicking a button to send the request?). Afterwards, the "Network" tab will be populated. You would see something like below:
As you could see, the url is posts.json which is what it should be. If you are instead seeing events and not events.json, then this is your problem; you need to make sure it's doing an events.json instead, or you can still do events, but update the "Accept" header in the request (as you would see in the screenshot, the value there should be "Accept: application/json"
P.S. all of what I said above is under the assumption that you are not rendering "manually" in the controller-action, and that you are not calling render manually (which will then do Rails defaults and Rails will render implicitly as what I have described in my answer above)
Try to add respont_to :json at the last line of the action method.
class EventsController < ApplicationController
def index
#events = Event.all
resond_to :json # add this line
end
end
I'm trying to use the pg_search gem in my rails application to search through numerous models from one search bar.
I have added the search bar:
<div id="search-bar">
<%= form_tag searches_path, method: :get do %>
<span><%= text_field_tag :query, params[:query] %><%= submit_tag "Search", name: nil %></span>
<% end %>
</div>
The route:
resources :searches
The searches controller index method:
def index
#results = PgSearch.multisearch(:query)
end
And the search index.html.erb:
<ul>
<% #results.each do |result| %>
<li><%= link_to result.searchable.title, result.searchable %></li>
<% end %>
</ul>
Each model that I want to be searchable has something like this in it:
include PgSearch
multisearchable :against => [:content, :author]
And I have an initializer like this:
PgSearch.multisearch_options = {
:using => {
:tsearch => {
:dictionary => "english"
}
}
}
I created a new item to make sure that it was added to the pg_search_documents table and checked the terminal to see that it was.
Yet when I enter a search query, nothing is coming up in the results table?
Here is the terminal output from the search:
Started GET "/searches?utf8=%E2%9C%93&query=Test" for 127.0.0.1 at 2019-01-16 13:16:48 +0000
Processing by SearchesController#index as HTML
Parameters: {"utf8"=>"✓", "query"=>"Test"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /Users/---/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Group Exists (0.2ms) SELECT 1 AS one FROM "groups" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:34
Category Exists (0.2ms) SELECT 1 AS one FROM "categories" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:37
Rendering searches/index.html.erb within layouts/application
ggPgSearch::Document Load (20.6ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('english', ''' ' || 'query' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))) ## (to_tsquery('english', ''' ' || 'query' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC
↳ app/views/searches/index.html.erb:7
Rendered searches/index.html.erb within layouts/application (24.2ms)
Group Load (0.3ms) SELECT "groups".* FROM "groups"
↳ app/views/layouts/application.html.erb:59
Category Load (0.2ms) SELECT "categories".* FROM "categories"
↳ app/views/layouts/application.html.erb:72
Completed 200 OK in 114ms (Views: 88.4ms | ActiveRecord: 21.9ms)
The ul tags are present on the page, but no li items, and I am sure that the term I am putting in was within the item I created.
How come it isn't picking up any results? Many thanks
Did you do the following?
$ rails g pg_search:migration:multisearch
$ rake db:migrate
It's required for multisearching. Also existing items may not be added to the document as you already know. You would need to "rebuild" as stated in the docs. When you made a new item for testing, did you save it properly?
Here are the docs I found for the pg gem:
https://github.com/Casecommons/pg_search
First post, so i'm a newbie in StackOverflow. I'm trying for several days to make appear a Return button on a page form but only on a specific one.
So, I was advised to use backlink to make it appears.
Here's my code from the form where I want the return button
<% if #backlink.present? %>
<div class="spacer30"></div>
<% if #backlink == 'infos' %>
path = membre_path(menu: 'infos')
<% end %>
<% end %>
<%= link_to "Retour", path, class: "btn-rounded btn-turquoise btn-small" %>
Here's my code controller
def edit
super do |user|
puts "TEST PARAMS BACKLINK #{params[:backlink]}"
#backlink = params[:backlink]
end
end
and my route's :
get 'change_password', to: 'users/registrations#edit'
put 'update' => 'users/registrations#update', :as => 'user_registration'
get 'edit_password', to: 'users/registrations#edit', :as => 'user_edit'
So i should have in my log my PUTS 'TEST PARAMS BACKLINK' but nothing appear, only :
Started GET "/change_password.1?backlink=infos" for ::1 at 2017-10-04 10:07:41 +0200
Processing by Users::RegistrationsController#edit as
Parameters: {"backlink"=>"infos"}
User Load (9.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendering users/registrations/edit.html.erb within layouts/application
Rendered users/registrations/edit.html.erb within layouts/application (14.4ms)
Rendered shared/_navbar.html.erb (4.0ms)
Rendered shared/_flashes.html.erb (1.1ms)
Completed 200 OK in 231ms (Views: 217.0ms | ActiveRecord: 9.1ms)
Any ideas why it doesn't work?
Many thanks.
I just had to delete some lines, here's what i changed from my registration controller :
def edit
#backlink = params[:backlink]
super
end
This way, it appears exactly the way I wanted to.
Many thanks :)
I'm trying to do what I think should be simple: do a simple edit on a single text string field with the default update action. But it just doesn't seem to work, despite many attempts and alterations.
There are no errors and the flash message responds successfully, but information isn't saved to the database at all:
routes.rb
resources :interviews do
resources :invitations do
put :accept
end
end
views/invitations/edit.html.haml
= simple_form_for [#interview, #invitation] do |f|
= f.error_notification
= f.input :testing
= f.submit 'Edit Invitstion', :class => 'button small'
controllers/invitations_controller.rb
def update
#invitation = Invitation.find(params[:id])
#interview = Interview.find(params[:interview_id])
#invitation.update_attributes(invitation_params)
if #invitation.update_attributes(invitation_params)
redirect_to edit_interview_invitation_path(#interview, #invitation), notice: "Your profile has been successfully updated."
else
render action: "edit"
end
end
private
def invitation_params
params.permit(:user_id, :interview_id, :invitation_id, :session_time, :workflow_state, :testing)
end
And here's the log:
Started PATCH "/interviews/3/invitations/7" for ::1 at 2016-05-15 19:01:52 +0800
Processing by InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"o0U5t0yPN0aE2er+DWK0uxqRGyp4ywfdSrEfvwiSQ3UUaOnr3Fd0raFs1IUqVzizKoqxRU0DDpmvysntB9fdhQ==", "invitation"=>{"interview_id"=>"3", "workflow_state"=>"invited", "session_time"=>"", "testing"=>"testtesttest"}, "commit"=>"Edit Invitstion", "interview_id"=>"3", "id"=>"7"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 7]]
Invitation Load (0.2ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", 7]]
Role Load (0.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1 [["id", 3]]
Interview Load (0.2ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", 3]]
CACHE (0.0ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", "7"]]
CACHE (0.0ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", "3"]]
Unpermitted parameters: utf8, _method, authenticity_token, invitation, commit, id
(0.1ms) BEGIN
Invitation Exists (0.4ms) SELECT 1 AS one FROM "invitations" WHERE ("invitations"."user_id" = 3 AND "invitations"."id" != 7 AND "invitations"."interview_id" = 3) LIMIT 1
(0.1ms) COMMIT
Redirected to http://localhost:3000/interviews/3/invitations/7/edit
Completed 302 Found in 12ms (ActiveRecord: 1.6ms)
Started GET "/interviews/3/invitations/7/edit" for ::1 at 2016-05-15 19:01:52 +0800
Processing by InvitationsController#edit as HTML
Parameters: {"interview_id"=>"3", "id"=>"7"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 7]]
Invitation Load (0.3ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", 7]]
Role Load (0.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1 [["id", 3]]
Interview Load (0.2ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", 3]]
Rendered invitations/edit.html.haml within layouts/application (6.1ms)
Completed 200 OK in 48ms (Views: 39.1ms | ActiveRecord: 1.6ms)
Check the format of your params object in your logs. Your invitation params are being passed within the params["invitation"] key, yet you're whitelisting and updating your object based on the params in the root params hash.
Also note that your logs are reporting that you're trying to update your invitation with unpermitted params:
Unpermitted parameters: utf8, _method, authenticity_token, invitation, commit, id
You can fix this by simply updating your invitation_params to use params[:invitation] rather than params like so:
def invitation_params
params.require(:invitation).permit(:user_id, :interview_id, :invitation_id, :session_time, :workflow_state, :testing)
end
Also, you might want to consider raising an error if you're trying to update a parameter that's not whitelisted to prevent these sorts of issues in the future.
In your rails config:
config.action_controller.action_on_unpermitted_parameters = :raise
I'm experiencing some unusual behaviour with my Rails 4 Application. Every single-time I click on a link_to inside my views, my controllers actions are being called twice. For example:
In my root_url I have this standard call for users_profile:
<%= link_to('User Profile', users_profile_path, :class => "logout-button") %>
When I click this link, my console shows the following output:
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:45:53 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.5ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.5ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.9ms)
Rendered users/sessions/profile.html.erb within layouts/application (5.2ms)
Completed 200 OK in 19ms (Views: 11.2ms | ActiveRecord: 2.5ms)
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:45:53 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.3ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.2ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.3ms)
Rendered users/sessions/profile.html.erb within layouts/application (4.1ms)
Completed 200 OK in 12ms (Views: 7.5ms | ActiveRecord: 1.2ms)
People often have this behaviour when there's a remote (JS for example) calling the method, but this is not my case. the weirdest part is that, if I put the direct URL to the users_profile_path on my browser. I only get one request on my rails console:
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:48:17 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.3ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.2ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.4ms)
Rendered users/sessions/profile.html.erb within layouts/application (4.2ms)
Completed 200 OK in 12ms (Views: 7.7ms | ActiveRecord: 1.1ms)
I'm getting this same result for every link inside my application, not only this one.
Rails 5/6
When I was clicking on a link, the whole controller was being called twice. I tried the accepted answer, but it does not work for me, so I just set turbolinks: false as below:
<%= link_to("Demo", #user, data: { turbolinks: false } ) %>
If you would like your app to still make use of Turbolinks then "Opting out of Turbolinks" on the code that is giving you problems is the way to go; just add data-no-turbolink.
I was having problems with using Bootstrap 3 and adding that fixed it. For example;
<li class="list-group-item" data-no-turbolink>
<%= link_to download_path(item) do %>
<button type="button" class="btn btn-success">Download</button>
<% end %>
</li>
I actually managed to solve this on my own.
There's a default gem that is installed with rails 4.0, it is called Turbolinks*.
For some reason, the javascript used in this gem* was causing the doubled requests on my server. That's why only GET requests were behaving like this, and POST requests were normal.
I still don't fully understand why gem* causes that, but after I removed the following line from my application.js file, the doubled requests stopped.
=// require turbolinks
Another solution is to add data-no-turbolink to the tag.
More info here: http://blog.flightswithfriends.com/post/53943440505/how-to-disable-turbolinks-in-rails-4