如何在数据库中保存标签?

时间:2016-08-05 09:08:40

标签: ruby-on-rails database forms tags

我想在我的表单中使用漂亮的标签,但我无法将其保存在我的数据库中。 当我使用丑陋的标签时,它可以工作:

 = f.input :all_tags, label: 'Tags', placeholder: 'Séparé par une virgule', input_html: {class: 'form-control'}

但是我希望现有的标签允许用户直接点击它以保存它。喜欢:

.tag
      %input{:type => "checkbox"}/
      %label{:for => ""} Diet
      %i.fa.fa-plus
      %i.fa.fa-check

所以在视觉上它是有效的,但正如你所看到的,我没有在场上说它被认为是被保存了,我也没有说要保存的价值。

有人可以帮助我吗?

为了更好地理解,我给你整个表格:

食谱/新:

= simple_form_for @recipe, html: {multipart: true} do |f|
  - if @recipe.errors.any?
    #errors
      %p
        = @recipe.errors.count
        prohibited this recipe from being saved:
      %ul
        - @recipe.errors.full_messages.each do |message|
          %li= message
  .row
    .panel-body
      = f.input :title, input_html: {class: 'form-control'}
      = f.input :description, placeholder: 'Dites nous ce que vous aimez dans cette recette ? où l\'avez-vous découverte ? avec quoi l\'accompagnée vous ? ...', input_html: {class: 'form-control'}
      = f.input :image, input_html: {class: 'form-control'}
      # ugly way
      = f.input :all_tags, label: 'Tags', placeholder: 'Séparé par une virgule', input_html: {class: 'form-control'}
      # pretty way
      .tag-wrapper
        .tag
          %input{:type => "checkbox"}/
          %label{:for => ""} Diet
          %i.fa.fa-plus
          %i.fa.fa-check
        .tag
          %input{:type => "checkbox"}/
          %label{:for => ""} Healthy
          %i.fa.fa-plus
          %i.fa.fa-check

      = f.button :submit, class: "btn btn-primary"

%script{:src => "https://use.fontawesome.com/6d77a862a3.js"}

recipes_controller:

def new
  @recipe = current_user.recipes.build
end

def create
  @recipe = current_user.recipes.build(recipe_params)
  respond_to do |format|
    if @recipe.save
      format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
      format.json { render :show, status: :created, location: @recipe }
    else
      format.html { render :new }
      format.json { render json: @recipe.errors, status: :unprocessable_entity }
    end
  end

private
  def recipe_params
    params.require(:recipe).permit(:title, :description, :image, :all_tags, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy])
  end

recipe.rb

class Recipe < ActiveRecord::Base
  has_many :taggings
  has_many :tags, through: :taggings
  belongs_to :user

  def all_tags
   self.tags.map(&:name).join(", ")
  end
end

0 个答案:

没有答案
相关问题