我正在关注这个答案:https://stackoverflow.com/a/8753998/561634并尝试根据用户制作一个user_post_id,就像答案中所描述的那样。
最终目标是拥有像website.com/username/posts/4这样的网址,其中4是来自该特定用户的第4个帖子,而不是像现在网站http://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
感谢您的帮助!
答案 0 :(得分:2)
这一行:
@post.user = current_user.id
应该是@post.user = current_user
或@post.user_id = current_user.id