Carl Edwards
Carl Edwards

Reputation: 14454

Finding permitted attributes for a Rails model

I'm familiar with the attributes method but what I'd like to do is only return the attributes that were permitted in my model's controller.

#users_controller.rb
def user_params
  params.require(:user).permit(:name, :birthday, :email)
end

What I'd like to do is create an enumerator that excludes unnecessary attributes like ids, timestamps and just include what was written in the example method above:

# show.html.erb
<% @user.user_params.each do |key, value| %>
  <p><b><%= key.titleize %>:</b> <%= value %></p>
<% end %>

Upvotes: 0

Views: 309

Answers (1)

Surya
Surya

Reputation: 16022

One way could be:

<% @user.attributes.slice('email', 'name', 'birthday').each do |key, value| %>
  <p><b><%= key.titleize %>:</b> <%= value %></p>
<% end %>

Also, you can make a method in your user.rb:

def user_params
  self.attributes.slice('email', 'name', 'birthday')
end

Now you can do:

<% @user.user_params.each do |key, value| %>
  <p><b><%= key.titleize %>:</b> <%= value %></p>
<% end %>

Upvotes: 1

Related Questions