我使用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
我的dbs:
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| %>
<div class="form-group">
<%= f.label :classify, "Classify and Tags" %><br>
<div class="input-group tags" >
<div class="tags_select">
<%= f.select :classify_id, Classify.all.collect { |c| [c.name, c.id]},{}, class: "form-control" %> ##I can get the classify_id in questions
</div>
<div class="tags_input col-md-12">
<%= 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 %>
我想要的是如何在tags table
,taggables table
中记录输入标签ID和名称,那么如何在问题show.html.erb
中显示标签名称?
Thansk非常感谢你的帮助。