在具有关系的表单中自动填充 ID
我创建了一个博客,它会有帖子,并且帖子是由用户创建的。 我的博客中已经有一个登录系统。 我已经建立了用户和他的帖子之间的关系。 现在,当我想添加新帖子时,我希望 Rails 自动填充 user_id 字段。
我应该添加隐藏字段并从保存它的会话中添加 user_id 吗?
或者 Ruby on Rails 是否有自己的方式来处理关系和使用 ID?
@编辑:
模型:
class Post < ActiveRecord::Base
validates_presence_of :subject, :body
has_many :comments
belongs_to :user
end
控制器:
....
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
...
I have created a blog, it will have posts, and the posts are created by the users. I already have a login system in my blog. And I have made the relation between a user and his posts. Now when I want to add a new post I want Rails to autofill the user_id field.
Should I add a hidden field and add the user_id from the session where I saved it in?
Or does Ruby on Rails have its own way to deal with relations and using IDs?
@edit:
the model:
class Post < ActiveRecord::Base
validates_presence_of :subject, :body
has_many :comments
belongs_to :user
end
the controller:
....
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想确保博主的帖子与正确的用户相关联,那么根本不要使用表单字段,因为最终用户可以更改它们的值。 最好依靠您拥有的登录系统,并在提交博客文章表单时执行类似的操作:
这假设您有一个
current_user
方法(可能在 application.rb 中),该方法可以获取通过您的登录系统的当前用户。 也许类似:并且还假设您已将
has_many :posts
放入 User.rb 中。If you want to ensure that a blogger's posts are associated with the correct user, then don't use a form field for this at all, since their values can be changed by the end user. Better to rely on the login system that you have and do something like this when the blog-post form is submitted:
This is assuming that you have a
current_user
method, perhaps in application.rb, that fetches the current user via your login system. Perhaps something like:and also assuming that you have put
has_many :posts
in User.rb.