【问题标题】:Rails: Nested routes for associated model recordsRails:关联模型记录的嵌套路由
【发布时间】:2012-07-01 15:42:20
【问题描述】:

我的主要目标是通过参数哈希传递个人资料 ID 和公司 ID,以便 更新两个模型之间的连接

模型已设置好,其中个人资料属于一家公司,一家公司可能有员工(个人资料),如底部代码所示。

我想使用员工控制器来添加、删除和显示与公司的个人资料关联。

但是当我尝试这样做时,我收到以下错误

No route matches {:action=>"show", :controller=>"employees", :company_id=>#<Profile id: 1, user_id: 1, first_name: "Aaron", last_name: "Dufall", created_at: "2012-06-30 07:49:00", updated_at: "2012-07-01 14:03:24", deleted: false, company_id: 1>}

当我将 delete 指定为如下代码所示的方法时,它何时显示

show.html.erb

<% @employees.each do |employee| %>
   <%= link_to full_name(employee), employee %>
   <%= link_to "Remove", company_employee_path(employee), :method => :delete %>
<% end %>

routes.rb

resources :companies do
  resources :employees
  resources :requests do
    put 'accept', :on => :member
  end
end

公司.rb

class Company < ActiveRecord::Base
  attr_accessible :name

  has_many :employees, 
           :foreign_key => 'company_id', 
           :class_name => "Profile"

  has_many :requests, as: :requestable

  validates :name,  presence: true, length: { maximum: 50 }, uniqueness: true

结束

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
  has_many :requests
  has_many :requested, as: :requestable

  attr_accessible :first_name, :last_name


  validates :first_name, presence: true
  validates :last_name, presence: true

end

【问题讨论】:

  • 您为什么要这样做?你想通过 PUT 动作更新什么?您需要 id 才能知道要更新的对象....也许您可以解释一下,您想用目标 url 完成什么。
  • 我想更新配置文件模型中的 association_id,我将通过当前用户方法或从按钮作为散列发送
  • 当您使用 DSL 命令 resources´ command in your routes. this can be overwritten by using resource´ 时,rails 总是将 /:id/ 添加到 PUT 方法中。

标签: ruby-on-rails controller routes nested-resources


【解决方案1】:

在 routes.rb 中使用 resource 而不是 resources

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多