Ruby on rails Rails类型不匹配问题
我遵循这个答案:并尝试根据用户创建一个用户post\u id,就像答案中描述的那样 最终目标是拥有类似website.com/username/posts/4这样的URL,其中4是该特定用户的第四篇文章,而不是像现在这样website.com/username/posts/4将在数据库中显示第四篇文章 我得到了这个错误:Ruby on rails Rails类型不匹配问题,ruby-on-rails,ruby,Ruby On Rails,Ruby,我遵循这个答案:并尝试根据用户创建一个用户post\u id,就像答案中描述的那样 最终目标是拥有类似website.com/username/posts/4这样的URL,其中4是该特定用户的第四篇文章,而不是像现在这样website.com/username/posts/4将在数据库中显示第四篇文章 我得到了这个错误: ActiveRecord::AssociationTypeMismatch in PostsController#create User(#2171866060) expect
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
我的模型如下所示:
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
谢谢你的帮助 这一行:
@post.user = current_user.id
应该是
@post.user=current\u user
或@post.user\u id=current\u user.id
我的posts表中有一个名为user的整数字段。很抱歉,应该在问题中提到,您的模型中的属于:user
,假设@post.user=
将获得user
的实例。为什么有一个名为user
的整数字段?如果你想遵循rails的惯例(你可能想),它可能应该是user\u id
。拥有一个关联和一个同名的列是一个非常糟糕的主意。