Friday, 16 October 2015

Use model association in create:


Use model association in create:

class BlogsController < ApplicationController
def create
@blog = Blog.new(params[:blog])
@blog.user_id = current_user.id
@blog.save
end
end

In this example, user_id is assigned to @blog explicitly. It's not too big problem, but we can save this line by using model association.

class BlogsController < ApplicationController
def create
@blog = current_user.blogs.build(params[:blog])
@blog.save
end
end

class User < ActiveRecord::Base
has_many :blogs
end

We define the association that user has many blogs, then we can just use current_user.blogs.build or current_user.blogs.create to generate a blog, and the current_user's id is assigned to the user_id of the blog automatically by activerecord.

No comments:

Post a Comment