Reputation: 3
I've a table called users that has an association has_and_belongs_to_many with the table departments. In the views/users/index.html.erb I want to display the departments that belongs to the users with a string Example: "Image, Direction". I already get this string form a user with the next code in my console:
> p1 = users.find(1)
> pd1 = p1.departments
> for dep in pd1 do
* t=t + dep.name+", "
>end
>t=t[0..-3]
my views/users/index.html.erb is like:
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= user.phone %></td>
<td><%= user.birthday.strftime("%d/%m/%Y") %></td>
<td><%= user.findDepartments %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
so I'm trying to use user.findDepartments to display the string. I defined the findDepartments method in the user controller:
def self.findDepartments
d=self.departments
for dep in d do
t=t+dep.name+ ", "
end
t=t[0..-3]
end
And the error that I receive is: undefined method `findDepartments' for #
EDIT: I've just realised how to do it. just erase the findDepartments method from the controller and put it into the user model with these modifications:
def findDepartments
t=""
d=self.departments
puts d
for dep in d do
t=t+dep.name+ ", "
end
t=t[0..-3]
end
Upvotes: 0
Views: 37
Reputation: 774
add an instance method, but use next code:
def deparments_names
self.departments.limit(3).collect(&:name).join(", ")
end
I don't know why you need to do [0..-3] but you can add this code after join(''). But I would say that you need also to check if there any departments.
Upvotes: 0
Reputation: 4053
you have to define findDepartments
as instance method
def findDepartments
d=self.departments
for dep in d do
t=t+dep.name+ ", "
end
t=t[0..-3]
end
Upvotes: 1