问题
I have a Post
model in my app, which belongs_to
a User
model, as well as a Location
model. Both the User
and Location
models use the has_many
relation with Post
.
Now, in my Post
controller's create action, I want to automatically associate the Post
with the currently logged in user (available to me as current_user
through Devise).
Also, it should associate with a pre-existing Location
if one exists with the same address
field (which he enters through the form), or create a new one and associate it with that if not.
My Post
model has a user_id
field as well a location_id
field for this purpose.
How do I accomplish the two associations automatically in the create action when the user creates a new Post?
回答1:
You'll need to use 2 statements.
@post = current_user.posts.build(params[:post])
@post.location_id = params[:location_id] # change this to whatever you're passing.
@post.save
来源:https://stackoverflow.com/questions/6983244/rails-associate-posts-with-user-and-location