简体   繁体   English

没有表格的Rails HABTM

[英]Rails HABTM without form

I have two models, Posts and Hashtags, in a HABTM relationship. 在HABTM关系中,我有两个模型,Posts和Hashtags。

My post controller looks like this: 我的后控制器看起来像这样:

 def create
    @post = current_user.posts.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, :notice => 'Post was successfully created.' }
        format.json { render :json => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.json { render :json => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

Now, when a user creates a new post, I want to do the following: 现在,当用户创建新帖子时,我想执行以下操作:

  • check for hashtags, words starting with a '#' 检查主题标签,以“#”开头的单词
  • if the hashtag already exists, link the Post and the Hashtag 如果#标签已经存在,则链接“帖子”和“标签”
  • if the hashtag does not exist, add it to Hashtags, and link the Post and the newly added Hashtag 如果#标签不存在,则将其添加到#标签中,并将Post和新添加的#标签链接起来

I suppose I have to do this after I do the posts.new, but I am unsure how to proceed. 我想我必须在执行posts.new之后执行此操作,但是我不确定如何继续。 Do I just edit the @post object? 我是否只编辑@post对象? If so, what format should it be in for @post.save to pick up on the link? 如果是这样,@ post.save使用哪种格式的链接?

Any suggestions would be greatly appreciated! 任何建议将不胜感激!

Ok, if you have your relationship setup properly you can run a regex on the post text to get all the hashtags out, then you could assign the hashtags with something like @post.hashtags = tags (tags being the hashtags you extracted from the text) and then save the model. 好的,如果您正确设置了关系,则可以在帖子文本上运行正则表达式以获取所有主题标签,然后可以为主题标签分配@post.hashtags = tags (标签是从文本中提取的主题标签) ),然后保存模型。

Another (less proper way I'd say), is to do the same but checking for the existence of the hashtag and creating them and saving them through the model, but good practice dictates that you do this through the relationship with the Post model. 另一个(我想说的不太恰当的方法)是做同样的事情,但是检查#标签的存在并创建它们并通过模型保存它们,但是良好的实践表明,您可以通过与Post模型的关系来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM