Rails: Associate posts with user and location

这一生的挚爱 提交于 2020-01-06 08:56:13

问题


I have a Post model in my app, which belongs_toa 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!