rails4有很多:如何在new.html.erb中获取值

6tdlim6h  于 2021-06-20  发布在  Mysql
关注(0)|答案(0)|浏览(254)

我使用rails4.2.8,ruby2.5.0。
我的关系是多层次的 questions , classifies , tags ,表关系如下:

我的模型:

class Question < ActiveRecord::Base
  has_many :taggables,:dependent => :destroy, inverse_of: :question
  has_many :tags, through: :taggables, :dependent => :destroy
  belongs_to :classify
  belongs_to :user
  accepts_nested_attributes_for :tags
  accepts_nested_attributes_for :taggables
end

class Tag < ActiveRecord::Base
  has_many :taggables, :dependent => :destroy,inverse_of: :question
  has_many :questions, through: :taggables, :dependent => :destroy,inverse_of: :question
  belongs_to :classify
end

class Classify < ActiveRecord::Base
  has_many :questions, :dependent => :destroy, inverse_of: :classify
  has_many :tags, :dependent => :destroy, inverse_of: :classify
  accepts_nested_attributes_for :questions
  accepts_nested_attributes_for :tags
end

class Taggable < ActiveRecord::Base
  belongs_to :question
  belongs_to :tag
  accepts_nested_attributes_for :question
end

我的数据库:

class CreateQuestions < ActiveRecord::Migration
      def change
        create_table :questions do |t|
          t.string :title
          t.text :content
          t.integer :classify_id
          t.timestamps
        end
      end
    end

class CreateTags < ActiveRecord::Migration
      def change
        create_table :tags do |t|
          t.string :name
          t.text :content
          t.integer :classify_id
          t.timestamps
        end
      end
    end

class CreateClassifies < ActiveRecord::Migration
  def change
    create_table :classifies do |t|
      t.string :name
      t.text :content
      t.timestamps
    end
  end
end

class CreateTaggables < ActiveRecord::Migration
  def change
    create_table :taggables do |t|
      t.integer :question_id
      t.integer :tag_id
      t.timestamps
    end
  end
end

我的控制器:

questions_controller.rb
def new
    @question = Question.new
    @question.taggables.build
    @question.tags.build
  end

classifies_controller.rb
def new
    @classify = Classify.new
    @classify.questions.build
    @classify.tags.build
  end

tags_controller.rb
def new
    @tag = Tag.new
    @tag.taggables.build
    @tag.questions.build
  end

我的 questions/new.html.erb ```
<%= form_for(@question) do |f| %>

<%= f.label :classify, "Classify and Tags" %>


<%= f.select :classify_id, Classify.all.collect { |c| [c.name, c.id]},{}, class: "form-control" %> ##I can get the classify_id in questions


<%= f.text_field :tag, class: "",multiple:"multiple",placeholder: "Please input the tags" %>

## There how can I get the input tags , and record the id and name in tags table , taggables table? Then how can I show the tags name in the question show.html.erb?

      </div>
    </div>
  </div>

<% end %>
我想要的是如何记录输入标签id和name `tags table` ,  `taggables table` ,那么如何显示问题中的标签名称 `show.html.erb` ? 
谢谢你的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题