My application has Dwellings and Roomies. I am building some authentication into the Dwelling view – only users who are roomies of the current dwelling should be able to view certain data – all other users will see a different view.
To enable this, I have created an is_roomie? method in the Users Controller. The method looks like this:
## is_roomie? method in Users_Controller.rb ##
def is_roomie?
roomie_ids = []
@dwelling.roomies.each do |r|
roomies_ids << r.id
end
roomie_ids.include?(current_user.id)
end
I call this method in the Dwelling view as follows:
## show.html.erb (Dwelling) ##
....
<% if current_user && current_user.is_roomie? %>
....
When I loaded the page after implementing this, I get the following NoMethoderror:
NoMethodError in Dwellings#show
Showing >/Volumes/UserData/Users/jraczak/Desktop/Everything/rails_projects/Roomie/roomie/app/views/dwellings/show.html.erb where line #5 raised:
undefined method `is_roomie?’ for #User:0x00000102db4608>
For some background, I did try this as a Dwelling method and moved this into the User model to no avail. Thanks in advance for any and all insight!
current_useris aUserobject, not aUsersControllerobject, so you cannot call the method you’ve defined on that object. When you think about it in this context, you’ll see that you should define this method onUser.Try something like this in app/model/user.rb:
Looking at this, though, we can improve the code by moving it into the Dwelling class in app/models/dwelling.rb:
You would then use this in the view with: