如何获取标签列表并将其与Rails API和React建立关联?

时间:2019-04-21 00:46:40

标签: javascript ruby-on-rails reactjs

设置后,一个简单的具有多个带有导轨的直通标签模型。这样的事情

Private Function PostHTTP(ByVal URL As String, ByVal PostStr As String) As String
    On Error Resume Next
    With CreateObject("MSXML2.XMLHTTP")
        .Open "POST", URL, False
        .SetRequestHeader "Content-type", "application/x-www-form-urlencoded"
        .Send (PostStr)
        PostHTTP = .ResponseText
    End With
End Function

我想在帖子创建时将帖子与标签相关联。

通常使用Rails View可以通过以下方式解决:

class Post < ApplicationRecord

 has_many :taggings
  has_many :tags, through: :taggings

  # Getter and Setter for all_tags vertial attribute

  def tag_list
    tags.map(&:name).join(', ')
  end

  def tag_list=(names)
    self.tags = names.split(',').map do |n|
      Tag.where(name: n.strip).first_or_create!
    end
  end

  def self.tagged_with(name)
    Tag.find_by_name!(name).posts
  end


end

但是要做出反应,您需要先获取列表,所以我试图

 <%= f.input :tag_ids, as: :select, collection: Tag.order(:name), label_method: :name, input_html: {multiple: true} %>

和Posts Controller上

resources :posts, except: :new do
    get 'tag_list', to: 'posts/new'
  end

在React方面

  def create
    @post = current_user.posts.build(post_params)
    @post.tag_list = params[:post][:tag_list].join(',')
    if @post.save

      render plain: 'Posted successfully', status: 201
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

并采用邮寄表格

componentDidMount() {
    fetch("/posts/new/tag_list")
      .then(response => response.json())
      .then(data => this.setState({ tag_list: data }));


   <Select
                    getOptionValue={option => option.name}
                    getOptionLabel={option => option.name}
                    isMulti
                    name="tag_list"
                    options={this.state.tag_list.map(({ id, name }) => ({
                      value: name,
                      label: name
                    }))}
                    className="basic-multi-select"
                    classNamePrefix="select"
                  />

但是仍然没有得到列表并在帖子中显示错误。 那么,有人可以在这种情况下启发一个变通方法吗?

0 个答案:

没有答案
相关问题