【问题标题】:Problem implementing edit/update functionality for model为模型实现编辑/更新功能的问题
【发布时间】:2019-05-13 19:18:45
【问题描述】:

当我尝试编辑 Job 模型的实例时,我尝试更新的属性设置为 Nil。

我尝试使用常规的 form_for 助手而不是 simple_form,因为我不知道 simple_form 是否需要额外的信息,例如要使用的操作和方法,但它不起作用。

edit.html.erb

<h1>Edit Job:</h1>
<br>
<%= simple_form_for @job do |f| %>
  <%= f.input :title, label: "Job title" %>
  <%= f.input :description, label: "Description" %>
  <%= f.button :submit %>
<% end %>

jobs_controller.rb

  def edit
    @job = Job.find(params[:id])
  end

  def update
    @job = Job.find(params[:id])
    @job.update(title: params[:title], description: params[:description])

    if @job.save
      redirect_to jobs_path(@job)
    else
      render "edit"
    end
  end

routes.rb

  resources :candidates
  resources :tenants, constraints: { subdomain: 'www' }, except: :index
  resources :jobs, path_names: { new: 'add' }
  get 'candidates/index'
  get 'candidates/new/:id' => 'candidates#new', :as => 'apply'
  get 'candidates/single/:id' => 'candidates#single', :as => 'view_candidate'
  get 'jobs/single/:id' => 'jobs#single', :as => 'single_job'
  get 'add-job' => 'jobs#new'
  get 'listings' => 'jobs#listings', :as => 'career_page'
  get 'listing/:id' => 'jobs#listing', :as => 'view_job'
  get 'welcome/index', constraints: { subdomain: 'www' }
  get 'dashboard' => 'tenants#dashboard', as: 'dashboard'
  constraints SubdomainConstraint do
    devise_for :users, path_names: { edit: 'account' }
    root 'tenants#dashboard'
  end

  root 'welcome#index'

没有错误,但是属性为 Nil,并且在 index 视图中显示的是 URL 而不是 @job.title(因为它的 Nil)

【问题讨论】:

    标签: ruby-on-rails edit controller-action


    【解决方案1】:

    我相信表单数据被包装到 params 中的键 :job 中,因此需要将 Job 的属性列入白名单

      def update
        @job = Job.find(params[:id])
        @job.update(job_params)
    
        if @job.save
          redirect_to jobs_path(@job)
        else
          render "edit"
        end
      end
    
    Private
      def job_params
        params.require(:job).permit(:title, :description)
      end
    

    【讨论】:

    • @user2570506 请随意投票,它对您以及未来的 SO 搜索者都有帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多