我正在关注这个答案:https : //stackoverflow.com/a/8753998/561634 并尝试根据用户创建一个 user_post_id ,就像答案中描述的那样。
最终目标是拥有像 website.com/username/posts/4 这样的网址,其中 4 是来自该特定用户的第 4 个帖子,而不是像现在这样 website.com/username/posts/4 将显示数据库中的第 4 个帖子.
我收到此错误:
ActiveRecord::AssociationTypeMismatch in PostsController#create User(#2171866060) expected, got String(#2152189000)
我的控制器创建方法如下所示:
def create
@post = Post.new(post_params)
@post.user = current_user.id
respond_to do |format|
if @post.save
format.html { redirect_to post_path(username: current_user.username, id: @post.id), notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
我的模型如下所示:
before_save :set_next_user_post_id
validates :user_post_id, :uniqueness => {:scope => :user}
def to_param
self.user_post_id.to_s
end
belongs_to :user
private
def set_next_user_post_id
self.user_post_id ||= get_new_user_post_id
end
def get_new_user_post_id
user = self.user
max = user.posts.maximum('user_post_id') || 0
max + 1
end
感谢大家的帮助!