Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to find the record in the controller before doing that, so you can do this in your controller action:</p> <pre><code>@topic = current_user.topics.find(params[:id]) </code></pre> <p>This will trigger an exception that you can easily catch or leave it.</p> <p>This is the best method to ensure data integrity, unless you're tinkering in other places of the app and you need to create Topics not in controllers.</p> <p>If you have such need, it's not bad to have a validation rule in the model to ensure major data integrity, but the model does need to know the user, that's only accessible from the controller.</p> <p>My recommendation is that you assign the user controller-side or just use scopes like:</p> <pre><code>current_user.topics.create(params[:topic]) </code></pre> <p>This way you are sure that the user is the same in question, and this invalidates the need to do another validation if it's the only place you're calling topic creation.</p> <p>If you are unsure and wants to game on with a validate_on_update I suggest creating a virtual attribute like so:</p> <pre><code>attr_accessor :this_user </code></pre> <p>But in any case you'd pass this via controller, since your model should know nothing about the current logged in user:</p> <pre><code>@topic = Topic.new(params[:topic]) @topic.this_user = current_user # or @topic.user_id and check for a attr_changed? </code></pre> <p><strong>Update</strong>: adding example as requested</p> <pre><code># @topic = Topic.new(params[:topic]) # @topic.this_user = current_user class Topic &lt; ActiveRecord::Base belongs_to :user attr_accessor :this_user def validate_on_update # Make sure that this_user is an instance of User, otherwise just use the id errors.add(:user, "Only the topic creator can update the topic") if user_id != this_user.id; end end </code></pre> <p><strong>Update</strong>:</p> <p>another suggestion is to use:</p> <pre><code>attr_readonly :user_id </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload