Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ruby on rails - What order do before filters occur in?

What order do before filters occur in? Specifically, what order do the before_action filters occur in, in regards to inheiritance? For example, will this work:

class A < ActionController::Base
  before_action :set_user

  def set_user
    @user = something
  end
end

class B < A
  before_action :set_post

  def show
    render @post
  end

  def set_post
    @post = @user.posts.first
  end
end

Will B#show work? What are the rules for filter order for future reference? I can't find any of this in the Rails documentation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest taking a look at the source code and API Docs on filters.

The default ordering should be

  1. :set_post
  2. :set_user

I think if you wanted to push :set_user to the top of the stack you could change the line in A to

prepend_before_action :set_user

Also worth pointing out, this isn't the only question on the topic; there are others here on SO.


As for your specific situation, it looks like you'll need to change A as I mentioned above in order to have @user be assigned by the time set_post in B runs.


As of 4.2.6 (probably changed in an earlier version), the ordering is now parent before child:

  1. :set_user
  2. :set_post

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...