我是 Rails 初学者,我使用以下方法创建了 3 个模型/控制器/视图rails generate scaffold
:
- 有很多主题的主题
- 有很多注释的主题
- 笔记
当我转到 时http://localhost:3000/subjects/1/topics
,Rails 会列出空的主题列表,当单击“新主题”链接时,您将转到http://localhost:3000/topics/new
。
我应该以及如何获取“新主题”的链接以将用户带到http://localhost:3000/subjects/:id/topics/new
而不是http://localhost:3000/topics/new
以及应该将新主题表单提交给http://localhost:3000/subjects/:id/topics/new
而不是http://localhost:3000/topics
?
视图/主题/索引:
<h1>Listing topics</h1>
<table>
<tr>
<th>Name</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @topics.each do |topic| %>
<tr>
<td><%= topic.name %></td>
<td><%= link_to 'Show', topic %></td>
<td><%= link_to 'Edit', edit_topic_path(topic) %></td>
<td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Topic', new_topic_path %>
控制器/主题:
def new
@topic = Topic.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @topic }
end
end
def edit
@topic = Topic.find(params[:id])
end
def create
@topic = Topic.new(params[:topic])
@topic.subject_id = params[:project_id]
respond_to do |format|
if @topic.save
format.html { redirect_to subject_path(@topic.subject_id), notice: 'Topic was successfully created.' }
format.json { render json: @topic, status: :created, location: @topic }
else
format.html { render action: "new" }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
新主题形式:
<%= form_for(@topic) do |f| %>
<% if @topic.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@topic.errors.count, "error") %> prohibited this topic from being saved:</h2>
<ul>
<% @topic.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
路线:
resources :subjects do
resources :topics do
resources :notes
end
end
resources :notes
resources :topics
resources :subjects
root :to => 'subjects#index'