【问题标题】:Tag model on another Rails在另一个 Rails 上标记模型
【发布时间】:2019-01-13 14:17:14
【问题描述】:

我想在我的帖子模型上标记我的产品模型。

post.rb

 has_many :taggings
 has_many :products, through: :taggings

product.rb

has_many :taggings
has_many :posts, through: :taggings

tagging.rb

belongs_to :post
belongs_to :product

在我的帖子视图中,我有一个产品列表。我希望当用户点击一个产品时,它会通过 post 方法创建一个新的产品/帖子链接。

我可以使用什么链接?如何设置控制器和参数?

感谢您的帮助

【问题讨论】:

  • 您如何创建帖子和产品?我想,通过相应控制器中的创建操作?尝试使用创建操作和用户remote: true 选项编写 TaggingsController 来标记表单

标签: ruby-on-rails join model relationship


【解决方案1】:

如果您想让用户一次创建多个标签,您只需在帖子的表单中添加一个选择/复选框即可。

<%= form_for(@post) do |f| %>
  # ...
  <div class="field">
    <%= f.label :product_ids %>
    <%= f.collection_select :product_ids, Product.all, :name, :id %>
  </div>
<% end %>

def post_params
  params.require(:post)
        .permit(:foo, :bar, product_ids: [])
end

Rails 会自动在连接表中创建记录。

如果您希望用户一一创建链接,您需要设置一个nested route

Rails.application.routes.draw do
  # ...
  resources :posts do
    resources :taggings, only: :create
  end
end

然后您需要在posts/show.html.erb 页面上为每个产品设置一个表单:

<ul>
  <% @post.products.each do |product| %>
    <li>
    <%= product.name %>
    <%= form_for [@post, product.taggings.new] do |f| %>
      <%= f.hidden_field :product_id %>
      <%= f.submit 'tag' %>
    <% end %>
    </li>
  <% end %>
</ul>

您可以稍后使用 CSS/JS 来美化它。

还有一个控制器来处理创建标记。

class TaggingsController < ApplicationController
  # POST /posts/:post_id/taggings
  def create
    @post = Post.find(params[:post_id])
    @tagging = @post.taggings.new(product: Product.find(params[:tagging][:product_id]))
    if @tagging.save
      redirect_to @product, success: 'Tagging saved.'
    else
      redirect_to @product, error: 'Tagging not saved.'
    end
  end
end

【讨论】:

  • 没有。这是一个完全独立的问题。
  • 非常感谢!可以加上destoy方法吗?
猜你喜欢
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多