I'm using ransack for searching users based on their company and active/inactive parameter. This works well when used individually, but I want to make use of both simultaneously. For example, if I select company first and then select active/inactive user, then the company name should persist.
Second, is there a facility in ransack to keep both values persisted when I click back or again on users?
UPDATE :
This is my view:
= search_form_for #search, url: search_users_path, method: :post, html: { class: 'sort' } do |f|
= f.label 'company:'
= f.select :company_id_eq,
Company.where('is_inactive = false').collect {|c| [ c.name, c.id ] },
{:include_blank => 'All company users'}, :'data-remote' => true, class: 'searchSelect searchUserSelect'
%div.sort_users
= f.label 'sort Users:'
= f.select :deleted_eq,
[raw("<option value= 0 selected=#{session[:deleted]}>Active Users</option><option value= 1>Inactive Users</option>")],
{}, :'data-remote' => true, class: 'searchSelect searchUserSelect', style: "width: 205px;"
This is my code in controller
#search = User.search(params[:q])
#users = #search.result.includes(:company).order("companies.name, last_name").page(params[:page]).per(20)
About filters persistence, I'm using the following before_action in ApplicationController:
def get_query(cookie_key)
cookies.delete(cookie_key) if params[:clear]
cookies[cookie_key] = params[:q].to_json if params[:q]
#query = params[:q].presence || JSON.load(cookies[cookie_key])
end
Then, say for an Intervention model, I have the following:
class InterventionsController < ApplicationController
before_action only: [:index] do
get_query('query_interventions')
end
def index
#q = Intervention.search(#query)
#interventions = #q.result
end
end
That way, if interventions_path is called without the q param, cookies['query_interventions'] is checked to access last persisted query. But when interventions_path is called with the q param, this new query is used and persisted for later use.
Also, if interventions_path is called with the clear param, the cookie is deleted.
Note this would raise a CookieOverflow exception if more than 4k are stored, but this is between 1024 and 4096 UTF-8 characters and it is usually ok. If not, you should use other kind of session storage.
Related
Consider the follow:
#posts = Post.all
render json: { success: true, data: #posts }
Now, each post will have parameters that are not required to be sent in this particular scenario (although it'll be in others), so I'd like to restrict the parameters sent and I thought maybe I could use map like so:
#posts = Post.all.map { |user| [user.email, user.first_name, user.last_name] }
render json: { success: true, data: #posts }
As you can imagine that doesn't work. Its very likely I'm using - or intending to use - map in a completely incorrect way and I'd appreciate your comments on how to achieve the above.
Thanks in advance!
You can make use of Hash#slice method to do something like:
#posts = Post.all.map { |user| user.as_json.slice("email", "first_name", "last_name") }
The #posts will be an array of Hash in this case, with each hash containing three key-value pairs.
It may be more appropriate to use a serializer.
You'll have to install the active_model_serializers gem first.
An example serializer for your Post controller would be:
class PostSerializer < ActiveModel::Serializer
attributes :email,
:first_name,
:last_name,
end
You'll use the serializer in this manner (I'm assuming you'd call it in the index method):
def index
posts = Mentor.all
render(
json: ActiveModel::ArraySerializer.new(
posts,
each_serializer: PostSerializer,
root: 'posts'
)
)
end
I am using the following gem: https://github.com/apneadiving/Google-Maps-for-Rails
I am trying to create #users inside my controller to only display users with the parameter "status" equal to "active"
def index
#users = User.all
#hash = Gmaps4rails.build_markers(#users) do |user, marker|
marker.lat user.latitude
marker.lng user.longitude
marker.title user.title
user_link = view_context.link_to user.title, user_path(user)
marker.infowindow "<h4><u>#{user_link}</u></h4><i>#{user.address}</i>"
end
end
In views/users/index.html.erb, I have a js function.
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
and in index.json.jbuilder I have:
json.array!(#users) do |user|
json.extract! user, :id, :latitude, :longitude, :address, :status, :title
json.url user_url(user, format: :json)
end
I have tried a few matching functions in my controller, but I am unsure of where to put the IF logic, ie. is it best suited to be in the index.json.jbuilder, the index.hmtl.erb or the controller?
Probably best in the Model.
class User < ActiveRecord::Base
def self.active
where(status: true)
end
end
Then in your controller
#users = User.active
Build some simple project and stack on using accepts nested attributes + form_for.
Now i have no problem with code, all work and save, but when i uncomment accepts_nested_attributes_fori have error or my model doesnt create (i try differente variant for last 5 days, but can t build this right..). I think i have problem in controller.. My code (which works without accepted_nested_attributes).
Model:
class Project < ActiveRecord::Base
belongs_to :user
has_one :j_project
has_one :p_project
# accepts_nested_attributes_for :p_project, :j_project
validates :user_id, :title, presence: true
end
View:
= form_for(#project) do |f|
= f.label :title
= f.text_field :title
= fields_for #p_project do |fa|
= fa.label :requester
= fa.text_field :requester
= fields_for #j_project do |ffa|
= ffa.label :j_login
= ffa.text_field :j_login
= ffa.label :j_password
= ffa.text_field :j_password
= f.submit "Save", class: "btn btn-large btn-primary"
Controller:
class ProjectsController < ApplicationController
def new
#project = Project.new
#p_project = #project.build_p_project
#j_project = #project.build_j_project
end
def create
#project = Project.new(project_params)
#project.user = current_user
#p_project = #project.build_p_project(p_project_params)
#j_project = #project.build_j_project(j_project_params)
if #project.save && #p_project.save && #j_project.save
flash[:success] = "New project was added successfully"
redirect_to user_root_path
else
render 'new'
end
end
private
def project_params
params.require(:project).permit(:title)
end
def p_project_params
params.require(:p_project).permit(:requester)
end
def j_project_params
params.require(:j_project).permit(:j_login, :j_password)
end
end
The problems was with validation:
project_id in j_project and p_project - when I dell them, all works well.
I edit my simple_form and controllers too with guides from internet... But problems, which I cant find in google - was with validation.
I have created an app that splits up a Student's Information into multiple forms.
Everything works fine, but when I try to render Form_One after a Validation Error, it does not render the appropriate URL/Page.
EX.
adults/1/students/2/form_one
turns into
adults/1/students/2
I need to render the same url so I can proceed to form_2.
MODELS
class Adult < ActiveRecord::Base
has_many :students
end
class Student < ActiveRecord::Base
belongs_to :adult
validates :firstName, :presence => true,
length: { maximum: 50 }
validates :lastName, :presence => true,
length: { maximum: 50 }
end
CONTROLLER
def update
#adult = Adult.find(params[:adult_id])
#student = Student.find(params[:id])
if #student.update_attributes(student_params)
###IF PASS REDIRECT TO THE NEXT FORM
if URI(request.referer).path == form_one_adult_student_path(#adult, #student)
redirect_to form_two_adult_student_path(#adult, #student)
elsif URI(request.referer).path == form_two_adult_student_path(#adult, #student)
redirect_to form_three_adult_student_path(#adult, #student)
else
redirect_to adult_path(#district, #adult)
end
else
error_messages = #student.errors.messages
#adult = Adult.find(params[:adult_id])
#student = Student.find(params[:id])
#student.errors.messages.merge!(error_messages)
###IF ERROR AND ON FORM_ONE RENDER FORM_ONE
if URI(request.referer).path == form_one_adult_student_path(#adult, #student)
###FOR SOME REASON THIS RENDERS adults/1/students/2
###BUT I NEED IT TO RENDER adults/1/students/2/form_one
render 'form_one'
end
end
end
def form_one
#title = "Student Information"
#adult = Adult.find(params[:adult_id])
#student = Student.find(params[:id])
end
def form_two
#title = "Parent Information"
#adult = Adult.find(params[:adult_id])
#student = Student.find(params[:id])
end
ROUTES
resources :adults do
resources :students do
member do
get :form_one, :form_two
end
end
end
###FOR SOME REASON THIS RENDERS adults/1/students/2
###BUT I NEED IT TO RENDER adults/1/students/2/form_one
render 'form_one'
Try redirect_to instead of render.
Keep in mind the difference between rendering a template, and making an HTTP request. Try pretending you are an HTTP client and think about the requests and responses. Sometimes it helps to look through your server log to see which controller actions happen, in which order. Look for lines like Processing students#update or Redirecting to ....
In the future, you may want to try resourceful routes like #show instead.
I'm trying to attach a file "attachment" to my upload model. The attachment field in my db after creation is nil, and links link #upload.attachment.url just redirect to a parent object. Maybe I'm doing something wrong? I haven't used Carrierwave before.
# Model
require 'carrierwave/orm/activerecord'
class Upload < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
end
Went with the basics for for the attachment field
# Form
= form_for #upload, :html => { :multipart => true } do |f|
%br
= f.file_field :attachment
And more basics with the controller:
def create
#upload = Upload.new(params[:upload])
#upload.attachment = params[:file]
if #upload.save
redirect_to #upload
end
end
I'm not getting any errors in my console, but the :attachment string on the student model is always nil.
Thanks!
Why u have added the line
#upload.attachment = params[:file]
remove it. it will work. attachment string is null because there is not params file in the form.