0
社區has_many社區話題
它顯示了CommunityTopics的形式當我訪問example.com/shop/WALMART/topic/new
並在提交後創建新記錄。
但所有我輸入的數據將不會被保存,所有的人都變成空:(爲什麼我的嵌套表單不能正確提交數據?
我的代碼是
的routes.rb
resources :communities, :path => "shop", do
resources :community_topics, :path => "topic", :as => :'topic'
end
型號/ community.rb
def to_param
"#{community_name}"
end
community_topics_controller.rb #NEW
def new
@community = Community.find_by_community_name(params[:community_id])
@community_topic = @community.community_topics.build
@community_topic.user_id = current_user.id
respond_to do |format|
format.html # new.html.erb
format.json { render json: @community_topic }
end
end
community_topics_controller.rb#創建
def create
@community = Community.find_by_community_name(params[:community_id])
@community_topic = @community.community_topics.build (params[:id])
respond_to do |format|
if @community_topic.save
format.html { redirect_to community_topic_path(@community.community_name, @community_topic), notice: 'Community topic was successfully created.' }
format.json { render json: [@community, @community_topic], status: :created, location: @community_topic }
else
format.html { render action: "new" }
format.json { render json: @community_topic.errors, status: :unprocessable_entity }
end
end
end
視圖/ community_topics/_form.html.erb
<%= form_for :community_topic, url: community_topic_index_url, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :community_id, :class => 'control-label' %>
<div class="controls">
<%= f.number_field :community_id, :class => 'number_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :user_id, :class => 'control-label' %>
<div class="controls">
<%= f.number_field :user_id, :class => 'number_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :title, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :title, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :body, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :body, :class => 'text_area' %>
</div>
</div>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
community_topic_index_path, :class => 'btn' %>
</div>
<% end %>
謝謝!!它的作品完美!請讓我確定這一點。第一行** @ community = Community.find_by_community_name(params [:community_id])**將選擇屬於哪個社區。對?並且你的答案,即第二行存在,使用以前形式輸入的參數進行記錄。對? – MKK
哦,你寫這行錯了aswel。如果你想在這裏找到相關的社區,只需要@community = Community.find(params [:community_id])'就行了。確保你也改變了新的行動。 –
如果我在社區模型中使用** to_param **,該怎麼辦?我正在使用名爲'community_name'的列作爲slug。我還應該使用** @ community = Community.find(params [:community_id])**嗎? – MKK