I'm trying to make a 'My Files' Page where the documents that users have uploaded are listed, but am having trouble filtering the documents per user.
Right now it is showing all documents uploaded, instead of the document associated with the user who uploaded it.
I use devise for users
I've tried to change the if statement to various different conditions but cannot seem to filter the documents associated with each user.
This is my code for the 'My Files' page:
<% #documents.each do |document| %>
<% if #document = current_user.documents.find_by(params[:user_id]) %>
<%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %>
<% end %>
<% end %>
This is my documents controller code for the myfiles page:
def myfiles
#documents = Document.all
end
Is there a simple way I can filter the documents that are associated with each user?
This method will show documents associated with current user only.
Controller file:
def myfiles
if current_user
#documents = current_user.documents
else
#documents = Document.all
end
end
View file:
<% #documents.each do |document| %>
<%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %>
<% end %>
Rails find_by returns the first record found. You're probably looking for where.
In the controller:
#documents = if params[:user_id]
current_user.documents.where(user_id: params[:user_id])
else
Document.all
end
In the view:
<% #documents.each do |document| %>
<%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %>
<% end %>
http://apidock.com/rails/ActiveRecord/FinderMethods/find_by
http://apidock.com/rails/ActiveRecord/QueryMethods/where
Related
I want a searchfunction that can search strings in Database.
What I tried is:
def search_user
#users_search = User.where("lastname LIKE ?", "#{#search}%")
redirect_to :back
end
For example if I type H it should show all Users with a beginning H
View:
<% if #users_search.present? %>
sdf
<% for user in #users_search %>
<%= user.lastname %>
<% end %>
<% end %>
Just looking to find out how to retrieve nested images for display on my front page. I have no problems with a standard model but have been unable to find how to bring has_many nested attribute through. All my nested Forms work fine just have neglected the front end.
eg. product has nested product_images. This doesn't look like a clever way of doing it as the last five images uploaded wont necessarily be related to the last five products added.
Could someone please share an example.
cheers
app/controller/home_controller.rb
class HomeController < ApplicationController
def index
#products = Product.last(5)
#product_images = ProductImage.last(5)
end
end
app/views/home/index.html.erb
<% #products.each do |pd| %>
<div><%= pd.product_name %>
<% end %>
<% #product_images.each do |pd| %>
<%= image_tag (pd.product_image(:medium)) %>
<% end %>
</div>
You can try this:
app/controller/home_controller.rb
class HomeController < ApplicationController
def index
#products = Product.last(5)
#product_ids = #products.collect(:id)
#product_images = ProductImage.where(:id => #product_ids).last(5)
end
end
app/views/home/index.html.erb
<% #products.each do |pd| %>
<div><%= pd.product_name %>
<% end %>
<% #product_images.each do |pd| %>
<%= image_tag (pd.product_image(:medium)) %>
<% end %>
So I have an interesting problem I'm working on. I am trying to create multiple objects of the same model in one view. I would like to display all the possible objects in my view, check boxes to select which ones to create, then submit and create all the corresponding objects.
Now the objects to select are gotten using an API request and returned in JSON format. The JSON is then displayed on the view for the user to select, then an array containing all the selected objects is sent back to the controller for creation.
Here is the relevant code that I've tried so far.
objects_controller.rb
def new
#possible_objects = <api call to get objs>
#objects = []
end
def create
params[:objects].each do |obj|
# create and save obj
end
end
objects/new.html.erb
<% form_for #objects do |f| %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag(api_obj["name"])%>
<%= api_obj["name"] %>
<% end %>
<%= f.submit %>
<% end %>
This is definitely not the right approach, as the form will not accept an empty array as a parameter. I'm not sure where else to go with this, any pointers in the right direction would be great. Thanks.
Thanks to MrYoshiji for pointing me in the right direction, this is what ended up working
objects_controller.rb
def
#possible_objects = <api call to get objs>
end
def create
params[:objects].each do |object|
new_obj = Object_Model.new( <params> )
new_obj.save
if !new_obj.save
redirect_to <path>, alert: new_obj.errors.full_messages and return
end
end
redirect_to <path>, notice: 'Successfully created.'
end
objects/new.html.erb
<%= form_tag objects_path(method: :post) do %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag 'objects[]', api_obj %>
<%= possible_object["name"] %>
<% end %>
<%= submit_tag 'Create'%>
<% end %>
Can you try the following?
# view
<% form_tag my_objects_path(method: :post) do |f| %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag 'objects[names][]', api_obj["name"] %>
<%= api_obj["name"] %>
<% end %>
<%= f.submit %>
<% end %>
# controller
def create
params[:objects][:names].each do |obj_name|
YourModelForObject.create(name: obj_name)
end
end
See this comment on the documentation of check_box_tag: http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag#64-Pass-id-collections-with-check-box-tags
I setup a search on my Products index page with PgSearch and Will-Paginate like this:
ProductsController
def index
#products = Product.text_search(params[:query]).page(params[:page]).per_page(5)
end
Products Model
include PgSearch
pg_search_scope :search,
def self.text_search(query)
if query.present?
search(query)
else
scoped
end
end
Product index page
<%= form_tag products_path, method: :get do %>
<%= text_field_tag :query, params[:query] %>
<%= submit_tag "Search", name: nil %>
<% end %>
<% if #products.blank? %>
No Results
<% else %>
<% #products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
But the problem I'm having now is that when I go to the Product index page, it shows all of the products when I want it to show nothing until a search is done. If the search is blank, return No Results but when you first hit the page it should show nothing. How would this be done?
You probably want to only run a text_search when a search parameter is present. You can put this logic into the view, the controller, or in the model.
In the view
<% if params[:query].present? %>
<% if #products.blank? %>
No Results
<% else %>
<% #products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
<% end %>
In the controller
def index
if params[:query].present?
#products = Product.text_search(params[:query]).page(params[:page]).per_page(5)
else
#products = Product.none # NOTE: Rails 4 only
end
end
In the model
# create a new method to encapsulate this search logic then use it in the controller
def self.search(value)
if value.present?
Product.text_search(value)
else
Product.none # NOTE: Rails 4 only
end
end
The old saying goes "fat model, skinny controller" so you might want to opt for the model method which will keep your controller and views simpler.
Put your display logic inside an if statement:
<% if params[:query].present? %>
<% if #products.blank? %>
No Results
<% else %>
<% #products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
<% end %>
Although I'm not familiar with how pg search works, you could do something like this in your method.
It's a nice refactoring as well as it avoids checking for existence and making decisions on params (code smell)
def self.text_search(query = "")
search(query)
end
As I said, not sure how pg_search works. Maybe when you browse for nothing, it returns all records. If that's the case, you can just have it return an empty array. Something like this would do
def self.text_search(query)
return [] if query.nil?
search(query)
end
On every page we have a condition like this for guest user.
<% if not_guest? %>
<% link_to "show", path %>
<% end %>
<% if not_guest? %>
<% link_to "delete", path %>
<% end %>
<% if not_guest? %>
<% link_to "edit", path %>
<% end %>
for which link should appear or not for guest user.
Are there any better ways to handle this scenario instead of writing the conditions for every link ?
Make a helper:
#helpers/application_helper.rb
def link_to_unless_guest(*args)
if not_guest
link_to(*args)
end
end
Then call like
<% link_to_unless_guest "show", path %>
def link_to_editable(*args)
options = args.extract_options![:parent]
html_tag = options.nil? ? nil : options.delete(:html_tag)
if not_guest
unless html_tag.nil?
content_tag html_tag,options do
link_to(*args)
end
else
link_to(*args)
end
end
end
<%= link_to_editable 'Show', path,:parent => {:html_tag => "li",:style => "border-top:1px solid #A2A2A2;",:class => "left"} %>
<%= link_to_editable 'Show', path %>
Modified helper which is provided by #Max as per my need.