我已将两个模型命名为。一个模型Topic
是Post
模型的父级,Post
与Tag
模型共享HABTM关系。没有一个模型有验证。
我想收集一个复选框,在主题和标签模型上设置数据,同时以单一形式提交帖子。我试过的任何时候都会遇到this problem。
我的问题:
控制器代码
before_filter :check_authentication, only: [:new]
before_filter :fetch_author, only: [:new, :create]
before_filter :fetch_post, only: [:show, :update, :edit, :destroy]
before_filter :fetch_topic, except: [:create]
def new
@topic = Topic.all
@post = @user.posts.build
@tag = @post.tags.build
end
def create
@post = @user.posts.build(params[:post])
@topic = @post.topic.build(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to [@topic, @post], notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
def update
if @post.update_attributes(params[:post])
redirect_to [@topic, @post], notice: 'Post was successfully updated.'
else
render :edit
end
end
def destroy
@post.destroy
redirect_to root_url([@topic, @post]), notice: 'Post deleted.'
end
private
def fetch_author
@user = User.find(session[:user_id])
end
def fetch_topic
@topic = Topic.find(params[:topic_id])
end
def fetch_post
@post = @topic.posts.find(params[:id])
end
这是我的表单
<%= form_for([:blog, @topic, @post]) do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content, sanitize: true, rows: 15%>
</div>
<div class="field">
<%= f.fields_for(:topic) do |build| %>
<%= build.label :topic_name, "Select a topic" %>
<%= collection_select(:post, :topic_id, Topic.all - [@post], :id, :topic_name, prompt: true) %>
<%end%>
</div>
<div class="field">
<%= f.fields_for(:tags) do |build| %>
<%= unless build.object.new_record?
build.check_box('_destroy') + build.label('_destroy', 'Remove Tag')
end%>
<%= build.label :tag_name, "Add Tag"%>
<%= build.text_field :tag_name %>
<%end%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:0)
是的,如果您需要这种类型的嵌套URL,则需要在每个redirect_to中定义命名空间。如果您没有此命名空间,则不能使用此嵌套URL。