Zhao Li
Zhao Li

Reputation: 5716

Rails: Creating a record with HABTM relationship

I've been doing this to create a record with a HABTM relationship:

@project = Project.new(:title => params[:project][:title],
                       :percent_complete => params[:project][:percent_complete])
@project.users << User.find(params[:project][:users])

I was wondering if there's a way to do the same thing, but more succinctly like this:

@project = Project.new(:title => params[:project][:title],
                       :percent_complete => params[:project][:percent_complete]
                       :users => User.find(params[:project][:users]))

Thank you for your time!

Upvotes: 4

Views: 1987

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

You can look into using accepts_nested_attributes_for in your Project model. I think it should do what you're looking for. To be honest though, I don't think it will buy you much and may complicate things more than you want.

Upvotes: 2

Related Questions