Ruby - Ajax: update session value when clicking on a link - ruby-on-rails

I have this ruby function in a controller
def updateSession value
case value
when 1,2
session[:value]=1
when 3,4
session[:value]=2
end
end
And I have different links that redirect to different pages.
I would like to change the session value when clicking on those links by calling the updateSession function
Is it possible and if so, how?

You could add a route for:
map.update_session 'update_session', :controller => "session", :action => "update"
Then I assume you're trying to get "value" from user parameters, so you could use the following to generate your links:
<%= link_to "Update Session - 1", update_session_path(:value => 1) %>
Then add the following to your controller to act based on the params provided:
def update_session
value = params[:value].to_i
case value
when 1,2
session[:value] = 1
when 3,4
session[:value] = 2
end
end

Related

Change View based on Option selected in select_tag in rails

I am trying to make a form where a user can wither post normally with their username like this - > normal
=form_for #confession , html: {multipart: true} do |f|
=f.label :Confess
=f.text_area :confession , require: true
=f.file_field :confessionimage
=f.select (:id,options_for_select(ID))
=f.submit 'Confess'
or Anonymously where their Names will be hidden and no one will know that who posted this post .. for this what I thought was I will make a user named anonymous in database and if a user select anonymous in select_form while posting they will post as an anonymous user.
for this in my controller I want something like this and main point that I can't understand is how can the controller know what user has selected ?
this is my controller
def index
#amitian = Amitian.where(institute: current_amitian.institute) if amitian_signed_in?
#confessions = Confession.where(amitian_id: #amitian.ids).order('created_at DESC') if amitian_signed_in?
#confession = current_amitian.confessions.build
#anonymous = Amitian.where(email: anonymous#anonymous.com)
# (if anonymous selected )
do #anonymous.confessions.build
end
To access this :id params you use confession_params[:id], or params[:confession][:id]
If you want to conditionally load different views you could use a respond_to block like this:
if confession_params[:id] == 1 #or params[:confession][:id] == 1
loaded_view = :foo
else
loaded_view = :bar
end
respond_to do |format|
format.html { render loaded_view }
end
This would load foo.html.erb or bar.html.erb, based on you #confession :id parameter, passed by your select on form_for tag, which loads parameter names based on your view's variable model.

ActionController::InvalidAuthenticityToken on delete form Rails 4

I have a problem with Rails 4 and deleting multiple items in a database.
I am working on creating an email inbox and I would like to move an item into the "trash folder" and after that I want to redirect the user to the trash page, where he can delete the item from the database.
My code:
routes.rb
namespace :admin do
resources :inboxes do
collection do
match 'destroy_multiple' => 'inboxes#destroy_multiple', via: ['post','delete']
get 'sent'
get 'trash'
end
end
end
controller :
def destroy_multiple
if params[:action] == 'trash'
#del = Inbox.where(:id => params[:delete]).destroy_all
else
#del = Inbox.where(:id => params[:delete]).update_all(:folder =>'trash')
end
redirect_to admin_inboxes_path
end
And finally, my form (slim) :
= form_tag destroy_multiple_admin_inboxes_path, method: :delete, class: "multiple_delete" do
input type="hidden" name="action" value = controller.action_name
- #inboxes.each do |msg|
- #username = msg.email.gsub(/([^.]+)#.+/, '\1').gsub(/[^0-9A-Za-z]/, ' ').split.map(&:capitalize).join(' ')
tr class=(msg.read == 1 ? nil : 'unread')
td.inbox-small-cells
label.checkbox-custom.check-success
= check_box_tag "delete[]", msg.id, false, class: "for_del", id: "delete_#{msg.id}"
label for="delete_#{msg.id}"
td.inbox-small-cells
i.fa.fa-star.inbox-started
td
a.avatar href="/fr/admin/inboxes/#{msg.id}"
span.bg-primary =#username[0]
td.view-message.dont-show = #username
td.view-message = msg.subject
td.view-message.inbox-small-cells
td.view-message.text-right = msg.created_at.strftime("%d/%m")
I can with this code successfully move mail to the "trash", but I cannot delete them from the database.
Thank you!
You need to add the authenticity_token to your form. Try:
form_tag destroy_multiple_admin_inboxes_path, method: :delete, class: "multiple_delete", authenticity_token: true do
If you're working with a specific active record object, use form_for instead of form_tag, and the csrf field will automatically be built into the form by rails. However, this is a good time to be using form_tag.
The alternative solution is to change the config config.action_view.embed_authenticity_token_in_remote_forms to false, but this will make your site less secure, and it's better to just add authenticity_token: true to your form_tag.
Here is the documentation on form_tag

Simple rails filters

I have simplest rails app, with scaffold Tent
here my controller#index for
def index
#tents = Tent
#tents = #tents.where(:brand => params[:brand]) if params[:brand]
#tents = #tents.where(:season => params[:season]) if params[:season]
end
view also standart, generated by scaffold
and here search witch should filter data
= form_tag tents_path, method: :get do
= label_tag "manufacturer"
= select_tag :brand, options_for_select(...), include_blank: true
= label_tag "seasons"
- Tent.pluck(:season).each do |season|
=check_box_tag 'season', season
=h season
= submit_tag 'Submit'
Problem 1:
When i submit from, and params are unselected(select or checl_boxes) i don't want to send this params but they are sent with empty
GET /tents?utf8=...&brand=&season=&commit=Submit
Problem 2:
When i check multiple checkboxes get request is somthing like
GET /tents?utf8=...&brand=Brand&season=4&season=3&commit=Submit
after this i expect that data will be selected for both values, but controller expected that both values is in the field, and returns zero results
any suggestuions?
UPDATE
probably my question solved in railscasts-111 (advanced search form)
About problem 2:
You need to specify season checkbox like below:
=check_box_tag 'season[]', season
But i didnt test it
Problem 2:
You need to write javascript wrapper for form to serialize and send data on submit

Using case statement in a helper

I haven't used case statements before and was wondering how to do the following.
I have a number of news pages, each having posts relevant to department, so the pages
/tynewyddnews
/woodsidenews
/outreachnews
/sandpipernews
On my home page I am grabbing the latest post from each of these and displaying them.
Post Model
def self.top_posts
#Array with each of the 4 departments - first record
top_posts = [
self.tynewydd_posts.first,
self.woodside_posts.first,
self.sandpiper_posts.first,
self.outreach_posts.first
]
#remove entry if nil
top_posts.delete_if {|x| x==nil}
return top_posts
end
tynewydd_posts for example is a scope
scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"
So if i am reading a post on the home page from tynewydd and want to create a link to /tynewyddnews or i am reading a post from woodside and want to link_to /woodside I have been advised that a case statement may help, but I am unsure on what to use as parameters, so my attempt so far is
def public_news
case Post.top_posts
when :tynewydd_posts == 'Ty Newydd'
link_to('...Read more', tynewyddnews_path)
when :woodside_posts == 'Woodside'
link_to('...Read More', woodsidenews_path)
end
end
And then in my view i can call the helper
<%= public_news %>
obviously a miserable attempt, firstly in examples I have seen a variable is being set when the case is being set? if someone could give some advice on how to achieve this it would be much appreciated
Try this variant:
def public_news
path = case
when Post.tynewydd_posts then tynewyddnews_path
when Post.woodside_posts then woodsidenews_path
...
else default_path end
end
link_to('...Read More', path)
end
when expression will fire up when expression is evaluated to true

How do I build link with specific part of params hash from previous request?

While I wouldn't normally create a page like this, please know this is a current constraint I can't change.
The page has a checkbox form as well as a table with links for THs that sort the table. I need to construct the TH link in a way that it retains the checkbox items already checked.
Checkbox constructed in View with Haml as:
= form_tag movies_path, :method => :get do
Include:
- #all_ratings.each do |rating|
= rating
= check_box_tag "ratings[#{rating}]", "1", (#ratingsarray.include?(rating) ? true : false)
= hidden_field_tag 'sort', #sort
= submit_tag 'Refresh'
Then for the table it has this for the TH
%th{:class => #classrelease_date}
%a#release_date_header= link_to "Release Date", movies_path(:sort=>'release_date', :params[:ratings]=>params[:ratings])
Ultimately I want the URL like "/moves/?sort=release_date&Ratings[PG]=1&Ratings[G]=1" where I am spitting out the ratings params back to the page as part of the URL. Or how to I pass the ratings params in any part of page where the existing controller code will read it.
Existing controller code access ratings from checkbox:
params[:ratings]
Since movies_path accepts hash as parameter, you can tailor params and then generate the URL with movies_path(params). Generally, you may need to remove "controller" and "action" from params.

Resources