社区has_many CommunityTopics
当我访问example.com/shop/WALMART/topic/new时,它显示了CommunityTopics的形式
并在提交后创建新记录
但我输入的所有数据都不会被保存,所有数据都会变空:(
我的代码是
的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 #create
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 %>
答案 0 :(得分:1)
看看这一行
@community_topic = @community.community_topics.build (params[:id])
你把错误的参数传递给了那个。应该是
params[:community_topic] :)