So, I've read in some book about tip "Use model association", which encourages developers to use build methods instead of putting ids via setters.
Assume you have multiple has_many relationships in your model. What's best practise for creating model then ?
For example, let's say you have models Article, User and Group.
class Article < ActiveRecord::Base
belongs_to :user
belongs_to :subdomain
end
class User &开发者_开发技巧lt; ActiveRecord::Base
has_many :articles
end
class Subdomain < ActiveRecord::Base
has_many :articles
end
and ArticlesController:
class ArticlesController < ApplicationController
def create
# let's say we have methods current_user which returns current user and current_subdomain which gets current subdomain
# so, what I need here is a way to set subdomain_id to current_subdomain.id and user_id to current_user.id
@article = current_user.articles.build(params[:article])
@article.subdomain_id = current_subdomain.id
# or Dogbert's suggestion
@article.subdomain = current_subdomain
@article.save
end
end
Is there a cleaner way ?
Thanks!
This should be a little cleaner.
@article.subdomain = current_subdomain
The only thing I can think of is merging the subdomain with params:
@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))
精彩评论