帖子属于主题和用户。如何使用 :topic_id 和 :user_id 创建帖子而不使用 attr_accessible 公开任何一个?
我正在创建一个传统论坛来学习/练习 Rails。正如您所熟悉的,用户可以创建主题和帖子。主题和帖子属于创建它们的用户,帖子属于它们发布的主题。 注意:帖子是主题的嵌套资源。
User Model
has_many :topics
has_many :posts
Topic Model
has_many :posts
belongs_to :user
Post Model
belongs_to :user
belongs_to :topic
因此,当用户创建新帖子时,该帖子需要一个 user_id
和一个 topic_id
。
我知道范围关联:
@user.posts.create(:title => "My Topic.")
@topic.posts.create(:content => "My Post.")
但这些示例仅分别设置了 user_id 和 topic_id,而不是两者。
我的问题
我怎样才能做这样的事情:
@topic.posts.create(:content => "This is Dan's post", :user_id => @dan.id)
无需通过attr_accessible :user_id
在Post模型中公开user_id
?
换句话说,我不想显式定义 :user_id
。
我尝试过类似的事情:
dans_post = @user.posts.new(:content => "the content of my post")
@topic.posts.create(dans_post)
无济于事。
I'm making a conventional forum to learn/practice Rails. As you're familiar with, Users can create Topics and Posts. Topics and Posts belong to the User that created them, and Posts belong to the Topic they were posted in. Note: Post is a nested resource of Topic.
User Model
has_many :topics
has_many :posts
Topic Model
has_many :posts
belongs_to :user
Post Model
belongs_to :user
belongs_to :topic
So, when a User creates a new Post, the Post needs a user_id
and a topic_id
.
I know about scoping associations with:
@user.posts.create(:title => "My Topic.")
@topic.posts.create(:content => "My Post.")
But those examples only set user_id
and topic_id
respectively, not both.
My Question
How can I do something like this:
@topic.posts.create(:content => "This is Dan's post", :user_id => @dan.id)
Without having to expose user_id
in the Post model via attr_accessible :user_id
?
In other words, I don't want to have to explicitly define :user_id
.
I tried things like:
dans_post = @user.posts.new(:content => "the content of my post")
@topic.posts.create(dans_post)
to no avail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
build
来构建关联,而不是new
,因为它将正确定义外键。要解决您的问题,请使用merge
将用户合并到帖子的参数中:Use
build
for building associations, instead ofnew
, as it will define the foreign key correctly. To solve your problem, usemerge
to merge in the user to the parameters for the post: