2012-02-14 18 views
0

我有命名空間兩個模型。一個模型TopicPost模型的父代,PostTag模型共享HABTM關係。沒有任何模型具有驗證。我的表單應該如何在Rails中查看?

我想收集使用複選框來設置主題和標記模型上的數據,同時將帖子嵌入到單個表單中。任何時候,我已經嘗試,但我遇到this problem

問題,我有:

  • 我應該如何擴大自己的狀態,控制器和模型,以避免this post發現的錯誤?
  • 我是否需要在每個redirect_to中聲明我的名稱空間?

控制器代碼

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

是你需要的,如果你想這樣的嵌套URL的每個redirect_to的定義你的命名空間。如果你沒有這個名字空間,你不能擁有這個嵌套的URL。

+0

謝謝,任何關於我主要問題的想法都非常感謝。 – rhodee 2012-02-14 16:04:34

相關問題