activerecord - Rails tip - "Use model association" -


so, i've read in book tip "use model association", encourages developers use build methods instead of putting ids via setters.

assume have multiple has_many relationships in model. what's best practise creating model ?

for example, let's have models article, user , group.

class article < activerecord::base   belongs_to :user   belongs_to :subdomain end  class user < activerecord::base   has_many :articles end  class subdomain < activerecord::base   has_many :articles end 

and articlescontroller:

class articlescontroller < applicationcontroller   def create     # let's have methods current_user returns current user , current_subdomain gets current subdomain     # so, need here way set subdomain_id current_subdomain.id , user_id 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 cleaner way ?

thanks!

this should little cleaner.

@article.subdomain = current_subdomain 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -