当我提交表单时,数据不会在帖子中发送并通过参数设置。我一生都无法弄清楚为什么。该表单位于计划/显示操作中,因此您会看到我在那里设置 @action 变量。它是通过JS发送的。
routes.rb
resources :plans do
resources :actions
end
action.rb
belongs_to :plan
计划.rb
has_many :actions
plans_controller.rb
def show
@plan = current_user.plans.includes(:actions).find(params[:id])
@action = Action.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @plan }
end
end
actions_controller.rb
before_filter :get_plan
def create
@action = @plan.actions.new(params[:action])
@action.user_id = current_user.id
@action.save
end
private
def get_plan
@plan = current_user.plans.find(params[:plan_id])
end
在views/actions文件夹中创建.js.erb
$('div#actions').prepend("<%= escape_javascript(render @action) %>");
$('div#<%= dom_id(@action) %>').effect('highlight');
_form.html.erb部分
<%= form_for ([@plan, @action]), remote: true do |f| %>
<%= f.text_field :desc %>
<%= f.number_field :days %>
<%= f.submit %>
<% end %>
通过 POST 发送的参数(缺少操作哈希 - 为什么?)
Started POST "/plans/1/actions"
Parameters: {"utf8"=>"✓", "authenticity_token"=>"**removed**", "commit"=>"Create Action", "plan_id"=>"1"}
数据库架构
create_table "plans", :force => true do |t|
t.string "name"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "actions", :force => true do |t|
t.string "desc"
t.integer "plan_id"
t.integer "days"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
最佳答案
操作是保留字。如果您将其称为其他任何名称( Controller 除外,这也是保留的),那么它将起作用。
http://guides.rubyonrails.org/action_controller_overview.html#routing-parameters
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values.
关于ruby-on-rails - 表单数据未通过 POST 以参数形式发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9362500/