如何实现具有多个通过关联的Update和destroy方法? Rails 5

时间:2018-08-30 06:28:32

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

嗨,我在我的posts_controller中进行了update和destroy方法时遇到了麻烦,我能够创建新的Posts,但是我无法更新,我想知道在销毁所有模型的同时如何销毁模型与其他模型的关联。

我的模特: 帖子模型

class Post < ApplicationRecord
 has_many :comments, dependent: :destroy
 has_many :has_categories
 has_many :categories, through: :has_categories

 validates :title, presence: true,
 length: { minimum: 5 }
 after_create :save_categories

 def categories=(value)
  @categories = value
 end

 private

 def save_categories
   @categories.each do |category_id|
    HasCategory.create(category_id: category_id, post_id: self.id)
   end
 end
end

Has_Category模型

class HasCategory < ApplicationRecord
  belongs_to :post
  belongs_to :category
end

类别模型

class Category < ApplicationRecord
  validates :name, presence: true
  has_many :has_categories
  has_many :posts, through: :has_categories
end

所以在我的部分表格中,新的和编辑操作是这样的

<%= form_with model: @post, local: true do |form| %>
  <!--Inputs before the categories-->
  <div>
    <label>Categories</label>
    <% @categories.each do |category| %>
      <div>
        <%= check_box_tag "categories[]", category.id %> <%= category.name %>
      </div>
    <% end %>
 </div>
 <div>
  <%= form.submit %>
 </div>
<% end %>

我的posts_controller创建和更新方法

def create
  @post = Post.new(post_params)
  @post.categories = params[:categories]
  if @post.save
    redirect_to @post
  else
    render :new
  end
end

def update
  @post = Post.find(params[:id])
  @post.categories = params[:categories]
  if @post.update(post_params)
    redirect_to @post
  else
    render :edit
  end
end

我的创建操作正在运行,但更新操作只是在check_box_tag之前更新输入。 我知道,我的Post模型上的 save_categories 方法是采用从表单接收的数组并创建HasCategory关联的方法,我该如何执行更新操作或什至销毁操作。考虑到“多对多关联”的情况?

1 个答案:

答案 0 :(得分:0)

has_many :categories, through: :has_categories行给您category_ids发帖。因此,您可以更改表格:

<%= form_with model: @post, local: true do |form| %>
  <!--Inputs before the categories-->
  <div>
    <label>Categories</label>
    <%= f.collection_check_boxes(:category_ids, @categories, :id, :name) 
  </div>
  <div>
   <%= form.submit %>
  </div>
<% end %>

和控制器:

def create
  # you need it here for correct rerendering `new` on validation error
  @categories = Category.all # or maybe you have here more complicated query
  @post = Post.new(post_params)      
  if @post.save
    redirect_to @post
  else
    render :new
  end
end

def update
  # you need it here for correct rerendering `edit` on validation error
  @categories = Category.all # or maybe you have here more complicated query        
  @post = Post.find(params[:id])
  if @post.update(post_params)
    redirect_to @post
  else
    render :edit
  end
end

private

def post_params
  params.require(:post).permit(:name, :some_other_post_params, category_ids: [])
end

您需要从Post模型中删除回调和categories=(value)方法。并在@categoriesnew动作中定义edit。如果等于Category.all,则可以将其设置为f.collection_check_boxes(:category_ids, Category.all, :id, :name)的形式,而无需定义@variable