The better way to make this association is to use the ActiveRecord setters provided by your belongs_to association.
Anti-pattern
post '/posts' do
@post = Post.new(params[:post)
@post.author_id = author.id
if @post.save
redirect "/posts"
else
render :new, locals: { messages: [ "There was an error!", @post.errors.full_messages ] }
end
end
Anti-Anti-Pattern:
post '/posts' do
@post = current_user.posts.build(params[:post)
if @post.save
redirect "/posts"
else
render :new, locals: { messages: [ "There was an error!", @post.errors.full_messages ] }
end
Always use the getters/setters provided. Your controller should not be reaching into your models and playing with the *_id attributes. It should be utilizing the getters and setters AR associations make for you.