Rails的要求:大专职位与用户和位置 [英] Rails: Associate posts with user and location

查看:146
本文介绍了Rails的要求:大专职位与用户和位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序,其中 belongs_to的 A 用户<α发表模型/ code>模型,以及一个位置模式。无论是用户位置机型使用的的has_many 关系发表

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.

现在,在我的发表控制器创建行动,我想自动关联的发表与当前登录的用户(提供给我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆