I have a Customer model that has the attribute private. This attribute is only visible for a total of 3 users in the database. If this method (check_box) gets checked by one of those 3 users the Customer is only visible by them.
I'm currently looping over all of the Customers like this:
<% #customers.where(:private => false).each do |single_customer| %>
My question is how can I accomplish when one of the 3 users is signed in that :private => false gets changed to #customers.each do |single_customer| because then I don't want to filter the private attribute anymore.
you need to change the build up of the loop. This snippet is a bit of meta programming, but you can do it like this:
# in the controller for example.
#customers = Customer.where(private: false)
#customers = Customer.all if current_user.is_my_special_user?
In the view you then simply do this: <% #customers.find_each do |customer| %>
use find_each for better performance if your collection is huge.
by default you use the private: false
if you detect your user is logged in, you overwrite the #customers
I am on Rails 4 and have a very simple question.
Say you have a User model which has_one Account and Account belongs_to the User
On the user show page, I would like to display user attributes as well as account attributes.
In the users_controller I could do it like this:
def show
#user = User.find(params[:id])
#account = #user.account
end
and then in the view:
<%= #user.name %>
<%= #account.id %>
OR
I could just set the user instance variable:
def show
#user = User.find(params[:id])
end
and in the view:
<%= #user.name %>
<%= #user.account.id %>
Is there a difference in these? Is one of them the 'Rails Way'? I may be over thinking this, but am just curious as to what is correct here.
I would argue that it's really a matter of preference. If I were the one writing it, I would assign it to a variable if it were going to be used multiple times across the view. If it is only used once, it seems redundant to assign it.
Recommended best practice is that you limit to one instance variable per controller action and #person.account.id (chaining) is not allowed.
See https://robots.thoughtbot.com/sandi-metz-rules-for-developers
Using decorators is good idea (e.g. Draper). The above example too simple to add another gem. You can use delegate in rails
See http://apidock.com/rails/Module/delegate
I am quite new at rails and I am having some trouble designing an admin dashboard.
What I want to achieve is this:
Have a list of multiple users from database.
Have the ability to select multiple records.
Have the ability to apply different actions to all of the
selected records.
The actions MAY not be directly translatable into SQL queries. (for example send an email)
I am not looking for a complete solution to the problem just a general description on how to approach this. I have a feeling I started on a wrong path.
So far I am doing this:
view
<%= form_tag("some_path", method: "get") do %>
<% #users.each do |user| %>
<%= check_box_tag "user_ids[]", users.id %>
<%end%>
<%= submit_tag("Send Email") %>
<%end%>
controller
def send_email
#recipients = User.find(params[:user_ids])
#recipients.each do |recipient|
Notifier.raw_email(recipient.email, params[:user_email][:subject], params[:user_email][:body]).deliver
end
end
This works as it is but i can only apply one action, send email that is.
I want to be able to choose an action to apply to all selected records or apply multiple actions to the selected records
Any thoughts?
You can use the send method to call methods of the model.
class User
def send_email(subject, body)
Notifier.raw_email(self.email, subject, body).deliver
end
end
Let /some_path also accept an array of actions
In our case actions = ['send_email']
In the action that some_path resolves to,
class SomeController < ActionController::Base
def some_action # that some_path resolves to in your config/routes.rb
#recipients = User.find(params[:user_ids])
#actions = params[:actions]
#recipients.each do |recipient|
#actions.each do |action|
recipient.send(action, params[:subject], params[:body])
end
end
end
end
In this way you can call multiple methods. Make sure you only accept valid action values or else the admin can simply call any of the User's methods.
You can have a select tag with the different actions you need.
Then on change of the select tag, you can update the action attribute of the form. eg, using jQuery.
$('#my-action-select').change(function() {
$('#myform').attr('action', $(this).val)
})
I'm trying to hide parts of my views depending on the User role.
So let's say I want only admins to be able to destroy Products. Besides the code in the controller for preventing regular users from destroying records, I would do the following in the view:
<% if current_user.admin? %>
<%= link_to 'Delete', product, method: :delete %>
<% end %>
The previous code works, but it's prone to errors of omission, which may cause regular users to see links to actions they are not allowed to execute.
Also, if I decide later on that a new role (e.g. "moderator") can delete Products, I would have to find the views that display a delete link and add the logic allowing moderators to see it.
And if there are many models that can be deleted only by admin users (e.g. Promotion, User) maitenance of all the ifs would be pretty challenging.
Is there a better way of doing it? Maybe using helpers, or something similar? I'm looking for something maybe like this:
<%= destroy_link 'Delete', product %> # Only admins can see it
<%= edit_link 'Edit', promotion %> # Again, only admins see this link
<%= show_link 'Show', comment %> # Everyone sees this one
I found these two questions that are similar to mine, but none of them answered my question:
Show and hide based on user role in rails
Ruby on Rails (3) hiding parts of the view
I strongly recommend pundit.
It allows you to create "policies" for each model. For your Product model you might have a ProductPolicy that looks something like this
class ProductPolicy < ApplicationPolicy
def delete?
user.admin?
end
end
In your view you can do something like this
<% if policy(#post).delete? %>
<%= link_to 'Delete', product, method: :delete %>
<% end %>
If later on you want to add a moderator role, just modify the policy method
class ProductPolicy < ApplicationPolicy
def delete?
user.admin? || user.moderator?
end
end
So I kind of figured a way to move the IFs out of the view. First, I override the link_to helper in my application_helper.rb:
def link_to(text, path, options={})
super(text, path, options) unless options[:admin] and !current_user.admin?
end
Then on my views I use it as:
<%= link_to 'Edit Product', product, admin: true, ... %>
This prevents regular users from seeing admin links, but for other html tags with content inside, such as divs, tables etc., an if would still be needed.
CanCan is another gem that lets you define "Abilities" per user role.
In views you can use something like if can? :delete, #post to check if the
user may delete that specific post.
Using the CanCan and Role gems, what is still needed is a way to Check The Route and see if "current_user" has permissions to access that Route based on their role(s) - then show/hide based on that.
This saves the user clicking on things and getting told they cannot see it - or us having to write per-item "if" logic specifying what roles can see what list-items (which the customer will change periodically, as roles are changed/refined) around every single link in one's menu (consider a bootstrap menu with 50+ items nested in groups with html formatting, etc), which is insane.
If we must put if-logic around each menu-item, let's use the exact same logic for every item by checking the role/permissions we already defined in the Ability file.
But in our menu-list, we have route-helpers - not "controller/method" info, so how to test the user's ability to hit the controller-action specified for the "path" in each link?
To get the controller and method (action) of a path (my examples use the 'users_path' route-helper) ...
Rails.application.routes.recognize_path(app.users_path)
=> {:controller=>"users", :action=>"index"}
Get just the controller-name
Rails.application.routes.recognize_path(app.users_path)[:controller]
=> "users"
Ability uses the Model for its breakdown, so convert from controller name to it's model (assuming default naming used) ...
Rails.application.routes.recognize_path(app.users_path)[:controller].classify
=> "User"
Get just the action-name
Rails.application.routes.recognize_path(app.users_path)[:action]
=> "index"
And since the "can?" method needs a Symbol for the action, and Constant for the model, for each menu-item we get this:
path_hash = Rails.application.routes.recognize_path(app.users_path)
model = path_hash[:controller].classify.constantize
action = path_hash[:action].to_sym
Then use our existing Abilty system to check if the current_user can access it, we have to pass the action as a symbol and the Model as a constant, so ...
<% if can? action model %>
<%= link_to "Users List", users_path %>
<% end %>
Now we can change who can see this resource and link from the Ability file, without ever messing with the menu, again. But to make this a bit cleaner, I extracted out the lookup for each menu-item with this in the app-controller:
def get_path_parts(path)
path_hash = Rails.application.routes.recognize_path(path)
model_name = path_hash[:controller].classify.constantize
action_name = path_hash[:action].to_sym
return [model_name, action_name]
end
helper_method :get_path_parts
... so I could do this in the view (I took out all the html-formatting from the links for simplicity, here):
<% path_parts = get_path_parts(users_path); if can?(path_parts[1], path_parts[0]) %>
<%= link_to "Users Listing", users_path %>
<% end %>
... and to make this not take all day typing these per-menu-item if-wraps, I used regex find/replace with capture and wildcards to wrap this around every list-item in the menu-item listing in one pass.
It's far from ideal, and I could do a lot more to make it much better, but I don't have spare-time to write the rest of this missing-piece of the Role/CanCan system. I hope this part helps someone out.
I have a users table. It contains a field "user_type".
I added the following scope stmts to the user.rb file:
scope :uemployee, where(:user_type => 'employee')
scope :uclient, where(:user_type => 'client')
scope :ucontractor, where(:user_type => 'contractor')
I created a view and I would like it to list he employees.
Here is the code I'm trying to use:
<% #users.uemployee.each do |user| %>
But, I get "undefined method `uemployee' for nil:NilClass"
What am I doing wrong?
Thanks
Looks like you wanted to do this:
<% User.uemployee.each do |user| %>
But this is considered to be a bad practice. You have to prepare you data in a controller and a view just cycles through it:
# in a controller's action
#users = User.uemployee
#in a view
<% #users.uemployee.each do |user| %>
But even this isn't the best approach. If you create the file views/users/_user.html.erb which shows the info about a particular user (current user will be available as a simple user variable, without the #) then you can simply write:
# in a view
<%= render #users %>
# remember, #users variable was set in your controller
then Rails will cycle through all the users "inside" the #users variable and show them one-by-one.
Your #users collection is nil