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
有具有相同名稱的關聯和列是一個非常糟糕的主意。 –