【问题标题】:Question regarding many-to-many relationship (Rails and React)关于多对多关系的问题(Rails 和 React)
【发布时间】:2022-06-12 22:26:19
【问题描述】:

我目前正在通过“Post_tags”在“Post”和“tags”之间创建多对多关系。我想要的是能够将 4 件事(标题、内容、标签、user_id)保存到我的后端,以便我可以显示或更新帖子。目前,我可以保存新帖子并更新没有标签的帖子。我当前的模型如下所示:

后模型

class Post < ApplicationRecord
    belongs_to :user
    has_many :post_tags
    has_many :tags, through: :post_tags
end

Post_tag 模型

class PostTag < ApplicationRecord
    belongs_to :post
    belongs_to :tag
end

标签模型

class Tag < ApplicationRecord
    has_many :post_tags
    has_many :posts, through: :post_tags
end

我正在使用 React 前端添加带有获取请求的新帖子

export default function Post({currentUser}){
    const[title, setTitle] = useState("");
    const[content, setContent] = useState("");
    const[tags, setTags] = useState("");
    const user_id = currentUser.id
    const navigate = useNavigate();

    function handleSubmit(e){
        e.preventDefault();
        const newPost = {
            title,
            content,
            user_id
        }
        fetch(`/post`, {
            method: 'POST',
            headers: {"Content-Type": 'application/json'},
            body: JSON.stringify(newPost),   
        }).then((r) =>{
            if (r.ok){
                r.json().then(navigate('/profile'))
                alert("New post created!")
            }else{
                alert("New post creation failed")
            }
        })

    }
    return(
        <div className="post-form-container">
            <form className="post-form" onSubmit={handleSubmit}>
                <label>Title</label><br/>
                <input 
                    className='title-input' 
                    type='text' 
                    onChange={(e) => setTitle(e.target.value)}  
                    value={title}>
                </input><br/>

                <label>Content</label><br/>
                <textarea 
                    className="content-input" 
                    type='text' 
                    onChange={(e) => setContent(e.target.value)}  
                    value={content} 
                    placeholder="Start typing~">
                </textarea><br/>

                <label>Tags: seperated by commas</label><br/>
                <input 
                    className="tags-input" 
                    type='text' 
                    onChange={(e) => setTags(e.target.value)} 
                    value={tags}>
                </input><br/>   

                <button className="post-btn" type="submit">Submit</button>
            </form>
        </div>

最后,我的架构文件是这样的:

ActiveRecord::Schema[7.0].define(version: 2022_06_07_003341) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "post_tags", force: :cascade do |t|
    t.integer "post_id"
    t.integer "tag_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.string "content"
    t.string "tags"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "tags", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "username"
    t.string "email"
    t.string "password_digest"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

我的问题是我应该如何将“标签”输入从前端发送到后端以保存在我的情况下?由于标签在单独的表中,我是否需要为标签创建另一个 POST 请求?我是 Rails 的初学者,请帮忙。

【问题讨论】:

    标签: reactjs ruby-on-rails


    【解决方案1】:

    accepts_nested_attributes_for :tags 添加到您的Post 模型

    class Post < ApplicationRecord
      has_many :post_tags
      has_many :tags, through: :post_tags
    
      accepts_nested_attributes_for :tags
    end
    

    tags_attributes: [{name: 'First Tag'}, {name: 'Second Tag'}] 到你的newPost 变量

    const newPost = {
      title,
      content,
      user_id,
      tags_attributes: [{name: 'First Tag'}, {name: 'Second Tag'}]
    }
    

    您还需要将tags_attributes: %i[name] 添加到Post 控制器中的强参数

    【讨论】:

      猜你喜欢
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多