问题
I have namespaced two models. One model Topic
is parent to the Post
model and Post
shares a HABTM relationship with the Tag
model. None of the models have validations.
I would like to gather use a checkbox to set data on the Topic and Tag model while submtting the post in a single form. Any time I have tried however I run into this problem.
Questions I have:
- How should I augment my form, controller and model to avoid the errors found in this post ?
- Do I need to declare my namespace in each redirect_to?
Controller code
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
Here is my form
<%= 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 %>
回答1:
Yes you need define your namespace in each redirect_to if you want this type of nested URL. If you have not this namespace you can't have this nested URL.
来源:https://stackoverflow.com/questions/9279651/how-should-my-form-look-in-rails