Reputation: 1173
I'm following this answer: https://stackoverflow.com/a/8753998/561634 and trying to make a user_post_id based on the user just like described in the answer.
The end goal is to have urls like website.com/username/posts/4 where 4 is the 4th post from that specific user, instead of like now where website.com/username/posts/4 would show the 4th post in the database.
I'm getting this error:
ActiveRecord::AssociationTypeMismatch in PostsController#create User(#2171866060) expected, got String(#2152189000)
my controller create method looks like this:
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
my model looks like this:
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
Thanks for all help!
Upvotes: 0
Views: 304
Reputation: 13581
This line:
@post.user = current_user.id
Should either be @post.user = current_user
or @post.user_id = current_user.id
Upvotes: 2