我在使用新的公共/私人主题方法时遇到了一些麻烦。我需要能够将public_viewable方法应用于我的主题范围。但是,我一直收到以下错误:
SyntaxError in TopicsController#index
/Users/ericpark/rails_projects/bloccit-2/app/models/topic.rb:7: syntax error, unexpected '(', expecting '}' scope :visible_to, -> { :publicly_viewable(user) } ^ /Users/ericpark/rails_projects/bloccit-2/app/models/topic.rb:20: syntax error, unexpected keyword_end, expecting '}'
Extracted source (around line #7):
5
6
7
8
9
10
validates :name, length: {minimum: 5}, presence: true
scope :visible_to, -> { :publicly_viewable(user) }
def publicly_viewable(user)
if user
我还在我的主题模型中定义了public_viewable方法:
class Topic < ActiveRecord::Base
has_many :posts, dependent: :destroy
belongs_to :user
validates :name, length: {minimum: 5}, presence: true
scope :visible_to, -> { :publicly_viewable(user) }
def publicly_viewable(user)
if user
topic_collection.all
else
topic_collection.where(public: true)
end
end
def privately_viewable
topic_collection.where(public: false)
end
end
主题控制器:
class TopicsController < ApplicationController
def index
@topics = Topic.visible_to(current_user).paginate(page: params[:page], per_page: 10)
authorize @topics
end
def show
@topic = Topic.find(params[:id])
@posts = @topic.posts.paginate(page:params[:page])
authorize @topic
end
def new
@topic = Topic.new
authorize @topic
end
def edit
@topic = Topic.find(params[:id])
authorize @topic
end
def create
@topic = Topic.new(topic_params)
authorize @topic
if @topic.save
redirect_to @topic, notice: "Topic was saved successfully."
else
flash[:error] = "Error creating topic. Please try again."
render :new
end
end
def update
@topic = Topic.find(params[:id])
authorize @topic
if @topic.update_attributes(topic_params)
redirect_to @topic
else
flash[:error] = "Error saving topic. Please try again."
render :edit
end
end
def destroy
@topic = Topic.find(params[:id])
authorize @topic
if @topic.destroy
flash[:notice] = "\"#{@topic.name}\" was deleted successfully."
redirect_to topics_path
else
flash[:error] = "There was an error deleting the topic."
render :show
end
end
private
def topic_params
params.require(:topic).permit(:name, :description, :public)
end
end
我对范围仍然很新,所以任何时候都会非常感激。