news_posts_controller.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. class NewsPostsController < ApplicationController
  2. before_action :set_news_post, only: [:show, :edit, :update, :destroy]
  3. before_action :check_can_edit, only: [:edit, :update, :destroy]
  4. before_action :check_correct_user, only: [:edit, :update]
  5. # GET /news_posts/1
  6. # GET /news_posts/1.json
  7. def show
  8. end
  9. # GET /news_posts/1/edit
  10. def edit
  11. end
  12. # POST /news_posts
  13. # POST /news_posts.json
  14. def create
  15. @news_post = NewsPost.new(news_post_params)
  16. @news_post.user = current_user
  17. respond_to do |format|
  18. if @news_post.save
  19. format.html { redirect_to @news_post.news_feed, notice: 'News post was successfully created.' }
  20. format.json { render :show, status: :created, location: @news_post }
  21. else
  22. format.html { render :new }
  23. format.json { render json: @news_post.errors, status: :unprocessable_entity }
  24. end
  25. end
  26. end
  27. # PATCH/PUT /news_posts/1
  28. # PATCH/PUT /news_posts/1.json
  29. def update
  30. respond_to do |format|
  31. if @news_post.update(news_post_params)
  32. format.html { redirect_to @news_post, notice: 'News post was successfully updated.' }
  33. format.json { render :show, status: :ok, location: @news_post }
  34. else
  35. format.html { render :edit }
  36. format.json { render json: @news_post.errors, status: :unprocessable_entity }
  37. end
  38. end
  39. end
  40. # DELETE /news_posts/1
  41. # DELETE /news_posts/1.json
  42. def destroy
  43. @news_post.destroy
  44. respond_to do |format|
  45. format.html { redirect_to news_posts_url, notice: 'News post was successfully destroyed.' }
  46. format.json { head :no_content }
  47. end
  48. end
  49. private
  50. # Use callbacks to share common setup or constraints between actions.
  51. def set_news_post
  52. @news_post = NewsPost.find(params[:id])
  53. end
  54. # Never trust parameters from the scary internet, only allow the white list through.
  55. def news_post_params
  56. params.require(:news_post).permit(:name, :content, :news_feed_id, :news_feed_type)
  57. end
  58. def check_can_edit
  59. redirect_to root_url unless @news_post.news_feed.can_post_news?(current_user)
  60. end
  61. def check_correct_user
  62. redirect_to root_url unless @news_post.user == current_user
  63. end
  64. end