Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 一对一关系的嵌套属性_Ruby On Rails_Ruby On Rails 3_Nested Attributes - Fatal编程技术网

Ruby on rails 一对一关系的嵌套属性

Ruby on rails 一对一关系的嵌套属性,ruby-on-rails,ruby-on-rails-3,nested-attributes,Ruby On Rails,Ruby On Rails 3,Nested Attributes,我有一家公司有一份认购书。现在我需要一个表单来添加或编辑公司和订阅,所以我使用“accepts\u nested\u attributes\u for”。这是公司模式的一部分: has_one :subscription, :dependent => :destroy accepts_nested_attributes_for :subscription 这是订阅模式的一部分: belongs_to :company 在控制器中,我有: def new @com

我有一家公司有一份认购书。现在我需要一个表单来添加或编辑公司和订阅,所以我使用“accepts\u nested\u attributes\u for”。这是公司模式的一部分:

  has_one :subscription, :dependent => :destroy
  accepts_nested_attributes_for :subscription
这是订阅模式的一部分:

  belongs_to :company
在控制器中,我有:

  def new
    @company = Company.new(:subscription => [Subscription.new])
  end

  def create
    @company = Company.new(params[:company])

    if @company.save
      redirect_to root_path, notice: I18n.t(:message_company_created)
    else
      render :action => "new"
    end
  end

  def edit
    @company = Company.find(params[:id])
  end

  def update
    @company = Company.find(params[:id])

    if @company.update_attributes(params[:company])
      redirect_to root_path, :notice => I18n.t(:message_company_updated)
    else
      render :action => "edit"
    end

  end
表格如下所示:

      <%= f.fields_for(:subscription) do |s_form| %>
        <div class="field">
            <%= s_form.label I18n.t(:subscription_name) %>
        <%= s_form.text_field :name %>
      </div>
  <% end %>

这就产生了两个问题:

  • “名称”字段仅在公司已有订阅时显示在编辑表单中,在添加新公司时不显示
  • 编辑公司并更改订阅的“名称”字段时,不会保存更改
我做错了什么


我正在使用Rails的3.1版

我认为您应该将新操作更改为:

def new
  @company = Company.new
  @company.build_subscription
end
有关更多信息,请参阅。然后,我认为您必须在公司定义列表中添加
subscription\u属性