0
我下面这样的回答:https://stackoverflow.com/a/8753998/561634并试图使基于刚才在回答这样描述的用户user_post_id。Rails的类型不匹配问题
最终目标是要有像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
感谢所有帮助!
我其实在我的被叫用户的职位表中的整数字段。对不起,应该提到,在 –
你'belongs_to的问题:user'在模型中,这将承担'@post.user ='会越来越User'的'一个实例。为什么你有一个名为'user'的整数字段?如果你想跟着轨公约(你可能想)这也许应该是'user_id'。 – gylaz
有具有相同名称的关联和列是一个非常糟糕的主意。 –