destroy method on Michael Hartl's Rails Tutorial Chapter 10

时间:2017-08-05 10:47:57

标签: ruby-on-rails railstutorial.org destroy

I'm going through Michael Hartl's Rails Tutorial, now I'm at the Chapter 10 and I cannot understand one thing:

When you delete one Micropost, where is the @micropost variable in the destroy method defined?
(I suspect it may be server by the link_to method, but I'm not sure if that makes sense or not)

View:

<%= link_to "delete", micropost, method: :delete, data: { confirm: "You sure?" } %>

Microposts controller:

def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
        redirect_to root_url
    else
        @feed_items = []
        render 'static_pages/home'
    end
end

def destroy
    @micropost.destroy
    redirect_to request.referrer || root_url
end

StaticPages controller:

  def home
      if logged_in?
          @micropost  = current_user.microposts.build
          @feed_items = current_user.feed.paginate(page: params[:page])
      end
end

(for whose not familiar with the tutorial, the form and the index of the Microposts are in the root_page, handled by static_pages)

if there is some code missing, here is the full project:
https://github.com/Salomanuel/Odin_Project-Ruby_on_Rails_Tutorial/tree/13-user-microposts

2 个答案:

答案 0 :(得分:1)

Referencing the code here https://github.com/Salomanuel/Odin_Project-Ruby_on_Rails_Tutorial/blob/375b4d7995d54337407f1736df0e7693a9de5ac6/app/controllers/microposts_controller.rb

You see at the top in the controller there is a line
before_action :correct_user, only: :destroy

This line tell rails that call current_user function before calling :destroy.

Now see in correct_user function we are getting id from params and declaring the @micropost variable.

def correct_user
  @micropost = current_user.microposts.find_by(id: params[:id])
  redirect_to root_url if @micropost.nil?
end

Hope this answer your question. You can read more about callbacks from here http://guides.rubyonrails.org/active_record_callbacks.html.

答案 1 :(得分:0)

ok, while doing some exercises I found out the solution. Turns out the @micropost variable was assigned by a private method called by a before_action:

Microposts controller:

before_action :correct_user,        only: :destroy   

private
    def correct_user
        @micropost = current_user.microposts.find_by(id: params[:id])
        redirect_to root_url if @micropost.nil?
    end

but still, is this considered good practice?

相关问题