Skip to content

Instantly share code, notes, and snippets.

@cdimartino
Last active February 12, 2016 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdimartino/7fa7babe78f917fc5cb4 to your computer and use it in GitHub Desktop.
Save cdimartino/7fa7babe78f917fc5cb4 to your computer and use it in GitHub Desktop.
AR Associations - use the setters

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment