Rails的要求:大专职位与用户和位置 [英] Rails: Associate posts with user and location
问题描述
我在我的应用程序,其中 belongs_to的
A 用户<α
发表
模型/ code>模型,以及一个位置
模式。无论是用户
和位置
机型使用的的has_many
关系发表
。
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
.
现在,在我的发表
控制器创建行动,我想自动关联的发表
与当前登录的用户(提供给我的 CURRENT_USER
通过设计)。
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).
此外,它应以$ P $关联对现有的位置
如果有存在相同的地址
现场(这是他通过形式进入),或创建一个新的,并将其与若不。
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.
我的发表
模式有一个 USER_ID
字段,以及一个 LOCATION_ID
为此领域。
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?
推荐答案
您需要使用2语句。
@post = current_user.posts.build(params[:post])
@post.location_id = params[:location_id] # change this to whatever you're passing.
@post.save
这篇关于Rails的要求:大专职位与用户和位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!