Ruby on rails - 为什么我的嵌套表单无法正确提交数据?



Community 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 #新

  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_topic = @community.community_topics.build (params[:id]) 

你传递了错误的参数。应该是

params[:community_topic] :) 

相关内容

  • 没有找到相关文章

最新更新