【发布时间】:2016-12-09 04:36:30
【问题描述】:
我感觉我错过了一些明显的东西......
Usergrant 记录未通过表单保存或更新 (User#update)。
许多用户可以通过连接表Usergrants与许多Grants相关联
class User < ActiveRecord::Base
has_many :usergrants
has_many :grants, through: :usergrants
accepts_nested_attributes_for :usergrants, allow_destroy: true
class Grant < ApplicationRecord
validates_presence_of :name
has_many :usergrants
has_many :users, through: :usergrants
end
class Usergrant < ApplicationRecord
belongs_to :user
belongs_to :grant
validates :user_id, :grant_id, :active, :percent, presence: true
end
控制器(具有强参数):
def edit
@title = "Edit User"
@user = User.find(params[:id])
@grants = Grant.all.where(active: true)
if current_user == @user
@page_title = "Edit your profile"
else
@page_title = "Edit "+@user.fname+"\'s profile"
end
if current_user.can_approve_this?(@user)
@disabled = false
@readonly_shower = "readonly-shower"
else
@disabled = true
@readonly_shower = ""
end
@active_def = @user.active
@salary_def = @user.pay_type
@super_array = super_array
@dept_array = dept_array
@pw_lang = "Change password"
session[:return_url] = back_uri
if @user.pay_type == "Salary"
@salary_hider = ""
@hourly_hider = "hidden"
else
@salary_hider = "hidden"
@hourly_hider = ""
end
end
def update
@user = User.find(params[:id])
@grants = Grant.all.where(active: true)
@user.salary_rate == 0.0 if @user.salary_rate.nil?
@user.hourly_rate == 0.0 if @user.hourly_rate.nil?
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to session[:return_url]
else
@dept_array = dept_array
@super_array = super_array
render 'edit'
end
end
def user_params
params.require(:user).permit(
:id, :fname, :lname, :active,
...
:usergrants_attributes => [:id, :user_id, :grant_id, :active, :percent])
end
还有用户表单:
<%= form_for( @user, remote: true) do |f| %>
...
<% @grants.each do |grant| %>
<%= f.fields_for :usergrant, @user.usergrants.find_or_initialize_by(user: @user, grant: grant) do |ug| %>
...
<%= grant.name %>
<%= ug.text_field :user_id, value: user.id %>
<%= ug.text_field :grant_id, value: grant.id %>
<%= ug.text_field :active %>
<%= ug.text_field :percent %>
<% end %>
<% end %>
...
<% end %>
我可以在控制台中创建 Usergrant 记录,它们会按预期显示在表单中。并且User.usergrant 和Grant.usergrant 正在按预期执行。
这是日志:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "user"=>{"id"=>"1",
"fname"=>"Chip", "lname"=>"...", "email"=>"...", "time_zone"=>"Eastern Time (US &
Canada)", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]",
"usergrants_attributes"=>{"0"=>{"id"=>"2", "user_id"=>"1", "grant_id"=>"1", "active"=>"0",
"percent"=>"0.0"}, "1"=>{"id"=>"1", "user_id"=>"1", "grant_id"=>"4", "active"=>"1",
"percent"=>"25.0"}, "2"=>{"id"=>"3", "user_id"=>"1", "grant_id"=>"5", "active"=>"0",
"percent"=>"0.0"}}}, "id"=>"1"}
我的缺点是什么?
【问题讨论】:
-
您是否检查过发送的参数与实际接收的参数结构是否匹配?!
-
日志结果已添加到帖子中。
标签: ruby-on-rails forms nested-forms ruby-on-rails-5 has-many-through