【问题标题】:How do I not use current_user in the model如何不在模型中使用 current_user
【发布时间】:2012-10-26 01:17:55
【问题描述】:

我有一个创建帖子的表单。此表单在帖子上也有标签,并且归用户所有。该表单使用虚拟属性:tag_ids。

我想做这样的事情,您可以在其中找到_or_create_by_name_and_user_id,然后传递 current_user.id。

def tag_ids=(tags_string)
    self.taggings.destroy_all
    tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
    tag_names.each do |tag_name|
      tag = Tag.find_or_create_by_name_and_user_id(tag_name, current_user.id)
      tagging = self.taggings.new
      tagging.tag_id = tag.id
    end
end

从我读到的内容来看,这不是它应该如何工作的。应该在 PostsContoller 创建方法中调用当前用户。

def create
  @post = Post.new(params[:post])
  @post.user = current_user
  respond_to do |format|
     if params[:commit]
     @post.save

... 结束

这是我卡住的地方。 如果参数传递了所有属性,我如何将 current_user id 注入具有 :name 和 :user_id 属性的标签模型中?

我还读到,由于我的关联,这应该可以工作。

用户 - has_many 帖子; has_many 标签

发布 - 属于_to用户; has_many 标签; has_many 标签通过标签

标签 - 有很多标签; has_many 通过标签发布帖子;属于用户

标记 - belongs_to 帖子;属于_to标签

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    您无法在模型中获取 current_user ,您必须显式传递,可能有几个黑客可以做到这一点,但简单的方法是,用户已经存储在帖子中,所以self.user.id 很有用 如果上面的方法在post模型中,post user就是tag user。

    Tag.find_or_create_by_name_and_user_id(tag_name, self.user.id)

    【讨论】:

    • 这对我不起作用。我得到“为 nil 调用的 id,它会错误地为 4——如果你真的想要 nil 的 id,请使用 object_id”这是在 self.user.id
    • self.user的值是什么
    • self.user的值为nil
    • 请记住,它是 nil,因为帖子尚未保存。而这个虚拟属性是要被保存的散列的一部分。
    • 如果你想访问model中的current_user你可以关注stackoverflow.com/questions/3742785/…
    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多