title: Rails - Anyone can add an item. Not good
body: <p>How do I prevent just anyone from submitting a form? Right now, any user can update a form on any other user's profiles, where they should only be able to touch theirs.</p>
  
  <p>Should I just hide the form if it's not on the current user's profile, or do something more secure inside the controller?</p>
  
  <p>For instance, I have a form to create a new book. In reality, the only time the form should be displayed is on the logged in user's profile page. The form should be hidden on other's profile pages.</p>
  
  <p><strong>Form:</strong></p>
  
  <pre><code>&lt;%= form_for @book do |f| %&gt;
      &lt;%= f.hidden_field :user_id, :value =&gt; @user.id %&gt;
      &lt;%= f.hidden_field :status, :value =&gt; "f" %&gt;
      &lt;%= f.text_field :title, :placeholder =&gt; "Title" %&gt;
      &lt;%= f.text_field :author, :placeholder =&gt; "Author" %&gt;
      &lt;%= f.submit 'Add Book', :value =&gt; "" %&gt;
  &lt;% end %&gt; 
  </code></pre>
  
  <p><strong>Edit:</strong></p>
  
  <p>I started to use CanCan, but still can't restrict access of creating books on other users' profiles.</p>
  
  <p>My new Ability.rb:</p>
  
  <pre><code>class Ability
      include CanCan::Ability
  
      def initialize(user)
          can :read, :all
          can :create, Book
      end
  end
  </code></pre>
  
  <p><strong>Before filter in application controller:</strong></p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
    before_filter :current_user
  
    def current_user
      User.current = current_user
    end
  end
  </code></pre>