在具有关系的表单中自动填充 ID

发布于 2024-07-16 06:43:55 字数 579 浏览 7 评论 0原文

我创建了一个博客,它会有帖子,并且帖子是由用户创建的。 我的博客中已经有一个登录系统。 我已经建立了用户和他的帖子之间的关系。 现在,当我想添加新帖子时,我希望 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往日情怀 2024-07-23 06:43:55

如果您想确保博主的帖子与正确的用户相关联,那么根本不要使用表单字段,因为最终用户可以更改它们的值。 最好依靠您拥有的登录系统,并在提交博客文章表单时执行类似的操作:

def create
  @post = current_user.posts.build(params[:post])
  if @post.save
    ...
  else
    ...
  end
end

这假设您有一个 current_user 方法(可能在 application.rb 中),该方法可以获取通过您的登录系统的当前用户。 也许类似:

def current_user
  @current_user ||= User.find(session[:user_id])
end

并且还假设您已将 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:

def create
  @post = current_user.posts.build(params[:post])
  if @post.save
    ...
  else
    ...
  end
end

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:

def current_user
  @current_user ||= User.find(session[:user_id])
end

and also assuming that you have put has_many :posts in User.rb.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文