0

如何使用户只能删除/编辑他/她发布的内容?不是所有的帖子?我当前的 song_controller 只有授权,允许用户在登录后编辑、销毁、更新。问题是,所有用户都可以编辑所有帖子。也就是说,我怎样才能只允许用户编辑他/她自己的帖子?并且无法通过其他帖子访问该功能?

歌曲控制器.rb

class SongsController < ApplicationController
  before_action :set_song, only: [:show, :edit, :update, :destroy]

  before_filter :authorize, only: [:create ,:edit, :update, :destroy]


  # GET /Songs
  # GET /Songs.json
  def index
    @songs = Song.all
  end

  # GET /Songs/1
  # GET /Songs/1.json
  def show
  end

  # GET /Songs/new
  def new
    @song = Song.new
  end

  # GET /Songs/1/edit
  def edit
  end

  # POST /Songs
  # POST /Songs.json
  def create
    @song = Song.new(song_params)

    respond_to do |format|
      if @song.save
        format.html { redirect_to @song, notice: 'Song was successfully created.' }
        format.json { render action: 'show', status: :created, location: @song }
      else
        format.html { render action: 'new' }
        format.json { render json: @song.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /Songs/1
  # PATCH/PUT /Songs/1.json
  def update
    respond_to do |format|
      if @song.update(Song_params)
        format.html { redirect_to @song, notice: 'Song was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @song.errors, status: :unprocessable_entity }
      end
    end
  end

  # Song /Songs/1
  # Song /Songs/1.json
  def destroy
    @song.destroy
    respond_to do |format|
      format.html { redirect_to songs_url }
      format.json { head :no_content }
    end
  end

  private

    def set_song
       @song = Song.find(params[:id])
     end

     def song_params
       params.require(:song).permit(:title, :artist, :bio, :track)
     end
  end
4

2 回答 2

2

您很可能拥有某种用户可以对其进行身份验证的用户模型。尝试在您的 User 模型上添加 has_many :songs 关联。在 Song 模型上添加一个名为 user_id 的外键以及 belongs_to :user。迁移。从 current_user 帮助器中提取用户的 id 并执行以下操作:

@user = User.find(current_user.id)
@songs = @user.songs #will give you only the songs the user added

这是一个很好的参考指南:http: //guides.rubyonrails.org/association_basics.html

于 2013-07-13T00:10:18.827 回答
1

如果您只希望用户看到他们发布的帖子,那么 jbearden 的建议会很好,尽管它不会阻止某人从地址行手动访问删除或更新等,这是不好的。

如果您希望用户查看所有歌曲但只能选择删除他们自己的歌曲等,那么您可能希望视图仅显示用户拥有的歌曲的编辑和删除链接(这将使用 jbearden 的 makin 想法歌曲与用户的关联) - 这有助于 UI,但仍不能解决您的身份验证问题。

可以使用 cancan gem 来处理身份验证(请参阅关于此的 railscasts - Ryan 是 gem 的作者)。cancan 需要一些时间来配置它,但在控制给定用户是否可以查看、编辑、删除等对象(如您的歌曲)方面效果很好。

祝你好运!

于 2013-07-13T02:13:21.967 回答