【问题标题】:From which controller should I be using to update these models, and how?我应该使用哪个控制器来更新这些模型,以及如何更新?
【发布时间】:2012-09-12 19:12:00
【问题描述】:

这是我正在使用的 3 个模型:

user.rb:

# == Schema Information
#
# Table name: users
#
#  id              :integer          not null, primary key
#  name            :string(255)
#  email           :string(255)
#  remember_token  :string(255)
#  password_digest :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation

  has_many :jobs
  has_many :restaurants, :through => :jobs

end

job.rb

# == Schema Information
#
# Table name: jobs
#
#  id            :integer          not null, primary key
#  restaurant_id :integer
#  shortname     :string(255)
#  user_id       :integer
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#

class Job < ActiveRecord::Base
  attr_accessible :restaurant_id, :shortname, :user_id

  belongs_to    :user
  belongs_to    :restaurant
  has_many      :shifts

end

餐厅.rb:

# == Schema Information
#
# Table name: restaurants
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Restaurant < ActiveRecord::Base
  attr_accessible :name

  has_many    :jobs
  has_many    :users, :through => :jobs
  has_many    :positions

end

我的场景是用户已经创建并输入到用户表中,但是现在用户想要:

  • 可能创建一家新餐厅(如果尚不存在)
  • 通过作业表在用户和餐厅之间创建链接,并
    • 可能同时在作业表中创建昵称

我将在表单中使用嵌套模型来完成此操作,但是我现在删除了所有与此相关的代码。原因是我试图从 Restaurants_Controller 中创建记录,如您所见,它位于“链”的底部。仔细想想,这似乎是错误的。除了在作业模型中链接 user_id 之外,我可以让 rails 为所有事情做这件事。

无论如何,我认为我对 Rails 的理解并不高。保存上述内容的逻辑应该在哪里(作为一个人在表单上点击“提交”的结果)?

【问题讨论】:

    标签: ruby-on-rails controller nested-attributes


    【解决方案1】:

    可能创建一个新餐厅,如果它不存在的话

    我认为这是这里的关键。用户并非一定按照您想象的流程创建餐厅。她正在创建一个工作,我认为这部分是用户和餐厅之间的关系(它也有一些关于该用户在餐厅轮班的其他知识)。

    从长远来看,我不清楚嵌套表单是否是正确的解决方案,但根据您的描述,我正在想象用户转到作业/新视图,其中包含一个发布到的表单jobs#create,它在该用户和餐厅之间创建关系。弄清楚restaurant_id 的来源以及创建尚未持久化的餐厅的流程中的哪个位置似乎是接下来要弄清楚的事情。

    【讨论】:

    • 谢谢,我也不确定。我很想听听你的其他想法,我正在吸收它!
    • 我认为您现在正在处理用户体验问题。一些选项:有一种在表单中选择餐厅的方法,并传入params[:restaurant_id]作为字段的值。允许它为nil,然后您需要控制器中的逻辑来决定如果是的话该怎么做。您是否重定向到餐厅创建页面(也许 this 是您的嵌套表单)?或者您可能在页面上有一个“添加新餐厅”按钮,该按钮加载了用于通过 javascript 创建餐厅的其他表单元素,而不是让 params[:restaurant_id] 成为 nil。很多选择。
    • 我会支持你,但我还不能......另外,我显然需要更多地了解 Ruby/Rails。谢谢!
    • 坚持下去!你问的问题很好。我自己只做了几个月的 Rails 开发。如果不是,我可能会对正确的解决方案有更强烈的意见!
    【解决方案2】:

    我认为您应该为这些事情使用 rails 资源。 Rails 资源为您提供不同字段的不同 url。 在 config/routes.rb 中像这样使用它

    resources :restaurent do
     resources :job 
    end
    

    这将为餐厅和工作创建更新网址,工作嵌套。 如果您不了解资源,请在 rails 指南中了解它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      相关资源
      最近更新 更多