How can I change params inside controller?
When I click the accept it will pass the status is approved but if diff <= 0 change status to rejected
View
<%= link_to 'Accept', friend_path(s, :request => {:status => 'Accepted'}), method: :put %>
into this
if diff <= 0
req_params[:status] = "Rejected"
#request.update(req_params)
end
end
private
def req_params
params.require(:request).permit(:status)
end
end
To modify your status param, you need to do the following:
params[:request][:status] = 'Rejected'
or
req_params[:request][:status] = 'Rejected'
Because your request take params like this:
Parameters => { some_param => 'Something', required => { permited1 => 'bla',
permited2 => 'bla2',
... } }
I hope that helps you
Related
I think I stated the title of this question right, but this is the issue:
I have the following in my SurveysController-
def pull_responses
call= "/api/v2/surveys/"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
survey_ids = response["surveys"].map { |s| s["id"] }
survey_ids.each do |x|
call= "/api/v2/surveys/#{x}/responses/?_completed=1"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://Fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
response_count = response["count"]
Survey.create(y: response_count)
end
end
helper_method :pull_responses
All I am trying to do is put the variable response_count in my Surveys view. I may not need Survey.create(y: response_count), but that was a peice of one of my attempts to get this to work. Essentially, I just want to write this in a view:
puts response_count
What is the proper way to put that response into a view?
You need to assign the value to an instance variable (by adding # before the name) so that it will persist to the view:
#response_count = response["count"]
then in the view you can print it like so:
<%= #response_count %>
I have view that created from сontributed API
=form_tag add_group_vk_vk_entries_path, method: :put do
-length_of_array = #vk_groups['message']['vk'].length
.row-fluid
-#vk_groups['message']['vk'][1..length_of_array].each do|item|
.span4
p= check_box_tag "vk_groups[]", item['gid']
p=item['name']
p=image_tag item['photo'], :size => "100x100",:class => "img-circle"
= submit_tag "ok"
I want to sent the data from this api to my controller by check_box_tag. I want to send not only item['gid'] i want to sent to my controller all data that i checked through one check_box_tag but i don't anderstand how.
In my controller
def add_group_vk
params[:vk_groups].each do |item|
if VkEntry.not_exists?(item) == true
VkEntry.create!(
:git => item
)
end
end
redirect_to vk_entries_url
end
i want something like this
def add_group_vk
params[:vk_groups].each do |item|
if VkEntry.not_exists?(item) == true
VkEntry.create!(
:git => item[:gid],
:name=> item[:name],
:ser=> item[:ser],
:photo=> item[:photo]
)
end
end
redirect_to vk_entries_url
end
First, I'm assuming that your above generates the check boxes with names like:
vk_groups[100], vk_groups[101],...
All you can really extract is a list of id's, they're in the the hash key, the value is not important.
params[:vk_groups] will yield a hash, iterate over the hash like so
def add_group_vk
params[:vk_groups].each do |key,val|
if VkEntry.not_exists?(key) == true
VkEntry.create!(
:git => key,
:name=> item[:name],
:ser=> item[:ser],
:photo=> item[:photo]
)
end
end
redirect_to vk_entries_url
end
As a result i done:
def add_group_vk
params[:vk_groups].each do |key,val|
item = eval val
if VkEntry.not_exists?(key) == true
VkEntry.create!(
:gid => key,
:name => item['name'],
:screen_name => item['screen_name'],
:is_closed => item['is_closed'],
:is_admin => item['is_admin'],
:is_member => item['is_member'],
:type_vk => item['type_vk'],
:photo => item['photo'],
:photo_medium => item['photo_medium'],
:photo_big => item['photo_big']
)
end
end
redirect_to vk_entries_url
end
In view
p= check_box_tag "vk_groups[#{item['gid']}]", item
Controller
class FeedEntriesController < ApplicationController
def index
#search = FeedEntry.search(params[:search])
#feed_entries = #search.page(params[:page])
#app_keys = AppKey.all
end
end
My feed_entries/index.html.erb
<%= link_to "Stared", {:controller => "feed_entries", :action => "index", :search => ['is_star = ?', true] }%>
feed_entries table contain is_star:boolean attribute. So, I just want to pass the parameter is_star == true into the params[:search].
But the above code is not working. Please some one help me.
Try
<%= link_to "Stared", {:controller => "feed_entries", :action => "index", :is_star => true } %?
And then you should be able to access in the controller using params[:is_star]
I'm getting the following error...
pry("serp")> session[self.to_sym] = "closed"
NameError: undefined local variable or method `session' for "serp":String
...when I try to set a session variable from within a monkeypatch on the String class. (Necessary so I can track the progress of a job in delayed job in order to load my search results only when they are ready.)
How can I set a session variable there? Or is there a better solution?
My code...
/config/initializers/string.rb:
class String
def multisearch
result = PgSearch.multisearch(self)
session[self.to_sym] = "closed"
return result
end
end
/app/views/searches/show.html.haml:
- if #term.present? && session[#term.to_sym] == "open"
%h1 Search In Progress
# then show spinning wheel animation etc
- else
%h1 Search Results
= form_tag search_path, :method => :get do
= text_field_tag "term", "Search term"
= submit_tag "Search"
- unless #results.blank?
# then show the search results etc
**/app/views/layouts/application.html.haml:
!!!
%html
%head
- if #term.present? && session[#term.to_sym] == "open"
%meta{:content => "5", "http-equiv" => "refresh"}/
/app/controllers/searches_controller.rb:
class SearchesController < ApplicationController
respond_to :html
filter_access_to :all
def show
if #term = params[:term]
session[#term.to_sym] = "open"
#results = #term.delay.multisearch
# other stuff...
end
end
end
Pass the session as a parameter.
class String
def multisearch session
result = PgSearch.multisearch(self)
session[self.to_sym] = "closed"
return result
end
end
Then
#term.delay.multisearch(session)
The answer was to stop fighting Ruby's OO nature and to build a Search model that could own everything I needed to access.
/app/models/search.rb:
class Search < ActiveRecord::Base
serialize :results
def multisearch
results = PgSearch.multisearch(self.term).to_a
self.update_attributes :results => results, :status => "closed"
return results
end
end
** /app/controllers/searches_controller.rb**:
class SearchesController < ApplicationController
respond_to :html
def show
if params[:term].present?
#search = Search.find_or_create_by_term(params[:term])
if #search.status.blank?
#search.delay.multisearch
#search.status = "open"
#search.save
elsif #search.status == "closed"
#search.update_attributes :status => nil
end
end
end
end
/app/views/searches/show.html.haml:
- if #search.present? && #search.status == "open"
# progress bar etc
- else
= form_tag search_path, :method => :get do
= text_field_tag "term", "Search term"
= submit_tag "Search"
- if #search.present? && #search.status.nil?
- unless #search.results.blank?
# show the search results
/app/views/layouts/application.html.haml:
- if #search.present? && #search.status == "open"
%meta{:content => "5", "http-equiv" => "refresh"}/
I want to have a Submit button. It updates one field on the submission; submission.state = :submitted
Now, I could make a custom route and a custom action and just post to that. But that seems really heavy-handed. Especially since I'll also have a reject button and possibly more. Needing a custom route & action for each of those seems downright silly to me.
It would be much nicer if I could do something like
button_to "Submit", submission_url(submission), :method => :put, :submission => { :state => :submitted }
Which would post to the submission's update method and update only the desired field.
But that doesn't work. How can I make it work? Or do you have a better idea of how to do this?
The pull request mentioned by #AugustinRiedinger has been merged and is now available as of Rails 4.1.0. Now just add the params option:
params: { state: :submitted }
It's not as concise, but without extending Rails, this will get me by:
= form_for submission, :html => { :class => "button_to" } do |f|
= f.hidden_field :state, :value => :submitted
= f.submit "Submit", :class => "link"
Add params:{} at the end, it will generate hidden_field
<%= button_to user.name, user, class:"btn btn-default", style:"", method: :patch, remote: true, params: { a_field: false, an_other_field:"a new value" } %>
I have something similar that works:
button_to "Submit", submission_url(submission, :submission => { :state => :submitted }), :method => :put
So, as from this rails pull request : https://github.com/rails/rails/pull/10471
Here is what you can do to have your custom button_to.
In application_helper.rb, add these lines:
module ApplicationHelper
// Unfortunately these 2 methods need to be redefined. I don't know how I could access the original ones.
def token_tag(token=nil)
if token != false && protect_against_forgery?
token ||= form_authenticity_token
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
else
''
end
end
def method_tag(method)
tag('input', type: 'hidden', name: '_method', value: method.to_s)
end
def button_to_with_params(name = nil, options = nil, html_options = nil, &block)
html_options, options = options, name if block_given?
options ||= {}
html_options ||= {}
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w(disabled))
url = options.is_a?(String) ? options : url_for(options)
remote = html_options.delete('remote')
params = html_options.delete('params') { Hash.new }
method = html_options.delete('method').to_s
method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe
form_method = method == 'get' ? 'get' : 'post'
form_options = html_options.delete('form') || {}
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
form_options.merge!(method: form_method, action: url)
form_options.merge!("data-remote" => "true") if remote
request_token_tag = form_method == 'post' ? token_tag : ''
html_options = convert_options_to_data_attributes(options, html_options)
html_options['type'] = 'submit'
button = if block_given?
content_tag('button', html_options, &block)
else
html_options['value'] = name || url
tag('input', html_options)
end
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
params.each do |name, value|
inner_tags.safe_concat tag(:input, type: "hidden", name: name, value: value.to_param)
end
content_tag('form', content_tag('div', inner_tags), form_options)
end
end
And to use it:
= button_to_with_params 'Awesome button', awesome_action_path, method: :put, :params => {:my_param => 'my_value'}
Enjoy! Have fun Railing!
If I read things correctly what you are effectively wanting to do something specific when a standard rails form is submitted in the standard way.
Notice that when a form is submitted using e.g.
f.submit "Save Changes"
then
params[:commit] = "Save Changes"
The GOOD thing about this is that it can allow you to do some appropriate branching in the controllers update action.
The BAD thing is that it's brittle. If one day you or someone else decides to change the button text, things break.. which is bad.
K
As of Rails 3.2.1 you can add additional params to the :html_options hash using the :form key.
http://apidock.com/rails/v3.2.1/ActionView/Helpers/UrlHelper/button_to
This did not exist prior to 3.2.1 so the more verbose solution of declaring a form with hidden attributes was required.