【问题标题】:object relationships and passing object ids to multiple controllers?对象关系并将对象 ID 传递给多个控制器?
【发布时间】:2012-11-03 14:51:42
【问题描述】:

我对做某事的最佳方式犹豫不决,希望得到一些建议。

我有以下型号:

class Plan < ActiveRecord::Base
  attr_accessible :description, :name, :user_id

  validates :name, :presence => true
end

class Planplace < ActiveRecord::Base
  attr_accessible :plan_id, :planplace

  validates :planplace, :presence => true
end

class Plandate < ActiveRecord::Base
  attr_accessible :plan_id, :plandate

  validates :plandate, :presence => true
end

一个计划可以有许多计划日期和计划地点。 我为每一个做一个非常基本的创建都有一个控制器。

class PlansController < ApplicationController

def create
    @plan = Plan.new(params[:plan])
    if @plan.save
        flash[:success] = "Created ..."
    else
        flash[:alert] = "placeplace save error ..."
    end
end   
end

class PlanplacesController < ApplicationController

    def create
        @planplace = Planplace.new(params[:planplace])
        if @planplace.save
            flash[:success] = "Created ..."
        else
            flash[:alert] = "placeplace save error ..."
        end
    end
end

class PlandatesController < ApplicationController

    def create
        @plandate = Plandate.new(params[:plandate])
        if @plandate.save
            flash[:success] = "Created ..."
        else
            flash[:alert] = "plandate save error ..."
        end
    end
end

我需要做的是有一个单一的视图来创建一个计划,并允许使用该 plan.plan_id 保存多个计划日期和多个计划地点。

在基本层面上实现这一目标的最佳方法是什么(我的目标是在不重新加载的情况下进行 ajax 调用以进行保存,但我离这还很远,我仍在努力学习)。

我是否将其放置在一个“新”平面视图中?我玩过一个表单,它使用 fields_for 在同一个表单中更新多个模型,但我想大致了解在此之前采取的最佳方法。

我知道我需要在模型中使用 has_many 和 belongs_to,但我不确定进行完整保存的最佳方式,因此关系是正确的。

希望我已经很好地解释了这一点。 非常感谢任何有关最佳方法的建议。

(请多多关照,我现在才学习 Rails 一个月)

---编辑--- 我已经在这里制定了模型以及如何传递我需要的对象。我不认为我问这个问题是正确的,因为我有点困惑。感谢所有看过它的人。

【问题讨论】:

    标签: ruby-on-rails activerecord table-relationships


    【解决方案1】:

    查看nested model forms

    就您而言,计划has_many :plandateshas_many :planplaces。 Plandate 和 Planplace belongs_to :plan。然后Plandates 和Planplaces 需要一个plan_id:integer 的列。

    【讨论】:

    • 我已将 plan_id 添加到两个表中。这对我来说是全新的,所以试图找到正确的解决方案,而不是“只是凑在一起,但它不是最好的”解决方案
    猜你喜欢
    • 2023-03-17
    • 2017-01-11
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多