标签: nested-forms

在Rails中使用accepts_nested_attributes_for +质量分配保护

假设你有这个结构:

class House < ActiveRecord::Base
  has_many :rooms
  accepts_nested_attributes_for :rooms
  attr_accessible :rooms_attributes
end

class Room < ActiveRecord::Base 
  has_one :tv
  accepts_nested_attributes_for :tv
  attr_accessible :tv_attributes
end

class Tv 
  belongs_to :user
  attr_accessible :manufacturer
  validates_presence_of :user
end
Run Code Online (Sandbox Code Playgroud)

请注意,Tv的用户无法故意访问.所以你有一个三层嵌套的表格,允许你在一个页面上输入房子,房间和电视.

这是控制器的创建方法:

def create
  @house = House.new(params[:house])

  if @house.save
    # ... standard stuff
  else
    # ... standard stuff
  end
end
Run Code Online (Sandbox Code Playgroud)

问题:你将如何填充user_id每个电视(它应该来自current_user.id)?什么是好的做法?

这是我在这看到的catch22.

  1. user_ids直接填充params哈希(它们非常嵌套)
    • 保存将失败,因为user_ids不可批量分配
  2. 在#save完成后为每个电视填充用户
    • 保存将失败,因为user_id必须存在
    • 即使我们绕过上述情况,电视也会暂时没有ids - 很糟糕

有任何体面的方式吗?

ruby ruby-on-rails nested-forms mass-assignment

6
推荐指数
1
解决办法
4515
查看次数

Rails:以嵌套形式保存许多新对象

我有2个型号:

视频:

class Video < ActiveRecord::Base
  belongs_to :user
  has_many :thumbnails
  attr_accessor :search, :saveable
  accepts_nested_attributes_for :thumbnails, :allow_destroy => true
en
Run Code Online (Sandbox Code Playgroud)

d

缩略图:

class Thumbnail < ActiveRecord::Base

  belongs_to :video

end
Run Code Online (Sandbox Code Playgroud)

我正在使用YouTubeG gem来搜索视频.

搜索返回的每个视频在视图中都有一个表单:

<% form_for :video, :url => videos_path, :html => { :class => :form } do |f| -%>
  <%= f.hidden_field :url, :value => video.unique_id %>
  <%= f.hidden_field :name, :value => video.title %>
  <%= f.hidden_field :user_id, :value => current_user.id %>
  <% if video.thumbnails.present? %>
    <%  f.fields_for :thumbnails, video do |t| %>
      <% …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails nested-forms

6
推荐指数
1
解决办法
3231
查看次数

动态嵌套表单link_to_add调用两次

我正在使用ryan bates nested_form gem来动态地向表单添加一些嵌套字段.

例如

<%= f.fields_for :phones do |phone_form| %>
<%= phone_form.text_field :phone_number %>
<% end %>
<%= f.link_to_add "Add a phone", :phones %></p>
Run Code Online (Sandbox Code Playgroud)

一切正常,但每次点击链接时都会添加两个空字段.

我放了一个断点 $('form a.add_nested_fields').live('click', function() ,看到它被叫了两次......

我在mac上使用chrome

javascript jquery ruby-on-rails nested-forms nested-form-for

6
推荐指数
1
解决办法
2290
查看次数

嵌套字段与mongodb

我正在尝试使用mongodb创建嵌套字段.为此,我正在使用gem mongomodel,它允许使用ruby和mongodb并且我正在使用gem nested_form来创建动态嵌套字段.我遇到了以下麻烦:

undefined method##的reflect_on_association'

我在互联网上发现的其他类似错误与我想用mongodb做的​​事情并不匹配.我是RoR的新手,我不知道如何解决这个问题.谁能帮我?

这是我的模特:

survey.rb

class Survey < MongoModel::Document
  property :name, String
  property :questions, Collection[Question]
  timestamps!

  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)

questions.rb

class Question < MongoModel::Document
  property :content, String
  timestamps!
end
Run Code Online (Sandbox Code Playgroud)

我的控制器:

surveys_controller.rb
class SurveysController < ApplicationController
  # GET /surveys
  # GET /surveys.json
  def index
    @surveys = Survey.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @surveys }
    end
  end

  # GET /surveys/1
  # …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails nested-forms mongodb nested-form-for

6
推荐指数
1
解决办法
729
查看次数

Rails - 如何在不使用accepts_nested_attributes_for的情况下管理嵌套属性?

我的问题是我遇到了accepts_nested_attributes_for的限制,所以我需要弄清楚如何自己复制该功能以获得更大的灵活性.(请参阅下文,了解究竟是什么让我失望.)所以我的问题是:如果我想模仿并增加accepts_nested_attributes_for,我的表单,控制器和模型应该是什么样的?真正的诀窍是我需要能够使用现有的关联/属性更新现有的AND新模型.

我正在构建一个使用嵌套表单的应用程序.我最初使用这个RailsCast作为蓝图(利用accepts_nested_attributes_for):Railscast 196:嵌套模型表单.

我的应用程序是带有作业(任务)的清单,我让用户更新清单(名称,描述)并在单个表单中添加/删除关联的作业.这很好用,但是当我将其合并到我的应用程序的另一个方面时,我遇到了问题:历史记录通过版本控制.

我的应用程序的一个重要部分是我需要记录我的模型和关联的历史信息.我最终推出了自己的版本(是我在描述我的决策过程/注意事项的问题),其中很大一部分是我需要创建旧版本的新版本的工作流程,对新版本进行更新,归档旧版本.这对于用户是不可见的,用户将该体验视为仅通过UI更新模型.

代码 - 模型

#checklist.rb
class Checklist < ActiveRecord::Base
  has_many :jobs, :through => :checklists_jobs
  accepts_nested_attributes_for :jobs, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end

#job.rb
class Job < ActiveRecord::Base
  has_many :checklists, :through => :checklists_jobs
end
Run Code Online (Sandbox Code Playgroud)

代码 - 当前表单(注意:@jobs在检查清单控制器编辑操作中被定义为此清单的未归档作业;因此是@checklist)

<%= simple_form_for @checklist, :html => { :class => 'form-inline' } do |f| %>
  <fieldset>
    <legend><%= controller.action_name.capitalize %> Checklist</legend><br>

    <%= f.input :name, :input_html => { :rows => 1 }, :placeholder => …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails nested-forms nested-attributes model-associations update-attributes

6
推荐指数
2
解决办法
7777
查看次数

Rails:nested_form gem remove不工作但添加工作

我的问题有点类似于问题nested_form gem add works但删除失败...为什么?.

我有一个产品编辑页面,其中产品的子类别在product_sub_categories中链接.要将子类别分配给产品,我使用了product_sub_categories的嵌套属性.因此,产品可以有多个sub_categories.

在产品型号中,

has_many   :product_sub_categories
has_many   :sub_categories, :through => :product_sub_categories
accepts_nested_attributes_for :product_sub_categories, :allow_destroy => true
Run Code Online (Sandbox Code Playgroud)

并在产品编辑视图中:

 <%= f.fields_for :product_sub_categories do |product_sub_category| %>
 <%= product_sub_category.collection_select :sub_category_id, @sub_categories, :id, :sub_category, {:include_blank => 'Select a Sub Category'} %>
 <%= product_sub_category.link_to_remove "Remove", :class => "subcatlink" %>
 <% end %>
Run Code Online (Sandbox Code Playgroud)

代码适用于添加子类别.但是当我删除子类别时失败了.日志给出:

 "product_sub_categories_attributes"=>{"0"=>{"sub_category_id"=>"1", "_destroy"=>"false", "id"=>"9"}, "1"=>{"sub_category_id"=>"1", "_destroy"=>"1", "id"=>"17"}},
 ProductSubCategory Load (0.2ms)[0m  [1mSELECT `product_sub_categories`.* FROM `product_sub_categories` WHERE `product_sub_categories`.`product_id` = 8 AND `product_sub_categories`.`id` IN (9, 17)
Run Code Online (Sandbox Code Playgroud)

虽然,我点击删除,它只是传递_destroy ="1",但不会破坏子类别.

任何人都可以告诉解决方案吗?

更新:

非常抱歉我的愚蠢错误.我没有看到正确的代码.在我复制的模型中

accepts_nested_attributes_for :product_sub_categories …
Run Code Online (Sandbox Code Playgroud)

nested-forms nested-attributes ruby-on-rails-3 ruby-on-rails-3.2

6
推荐指数
1
解决办法
1571
查看次数

Rails - 如何避免在视图中使用hidden_​​fields将值传递给控制器​​?

有没有办法可以避免hidden_field将视图中的值传递给控制器​​的方法?出于安全原因,我更喜欢控制器方法.不幸的@variables是,不支持价值配对strong_parameters.

编辑6/18美国东部时间下午1:00

  1. 我已将garages控制器重命名为appointments
  2. cars_controller不再创造新的appointment(正式的garages).在该中创建新约会 appointments_controller

我目前的结构


路线

Rails.application.routes.draw做

resources :techs, only: [:index, :show], shallow: true do
    resources :cars, only: [:new, :create]
end
Run Code Online (Sandbox Code Playgroud)

资源:约会

#For searchkick
resources :cars, only: [:show] do
    collection do
        get 'search'
    end
end

root "home#index"

end
Run Code Online (Sandbox Code Playgroud)

楷模

tech.rb

class Tech < ActiveRecord::Base
    searchkick

    has_many :appointments
    has_many :customers, :through => :appointments
    has_many :service_menus
    has_many :services
    has_many :cars
end
Run Code Online (Sandbox Code Playgroud)

service.rb

class Service < ActiveRecord::Base
    belongs_to …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails nested-forms ruby-on-rails-4

6
推荐指数
1
解决办法
458
查看次数

rails accepts_nested_attributes_for:reject_if无效

我试图覆盖autosave参数,因为我认为它无法完成.
我把它has_shipping_address从模型转移OrderShippingAddress模型,现在我有:

#the models..
class Order < ActiveRecord::Base

  belongs_to :billing_address
  belongs_to :shipping_address 

  accepts_nested_attributes_for :billing_address
  accepts_nested_attributes_for :shipping_address, :reject_if => proc { |attributes| attributes["has_shipping_address"] != '1' }

  def after_initialize                       
    self.build_billing_address unless billing_address
    self.build_shipping_address unless shipping_address
  end

end

class ShippingAddress < OrderAddress
  attr_accessor :has_shipping_address  
end

class OrderAddress < ActiveRecord::Base
  validates_presence_of :name
  #more validations here..
end   

#the view
<% form_for @order do |f| %>
  #...
  <% f.fields_for :shipping_address do |addr_f| %>
    <%= addr_f.check_box :has_shipping_address %>
    <%= …
Run Code Online (Sandbox Code Playgroud)

activerecord nested ruby-on-rails nested-forms

5
推荐指数
1
解决办法
5249
查看次数

使用Rails 4,强参数和Carrierwave上传文件

我正在移植一个使用Carrierwave到Rails 4的应用程序,但我遇到了强大的params问题.我有一个模特

accepts_nested_attributes_for :photos
Run Code Online (Sandbox Code Playgroud)

以下是上传图片的传递方式:

{
    # ...
    "model"=>
    {
        # ...
        "photos_attributes"=>
        {
            "1362752177921"=>
            {
                "image"=>"test.jpg",
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法弄清楚如何编写将接受的参数photos_attributes.

我试过.permit(photos_attributes: [])但它只是跳过它们,当我使用时permit!,uuid在保存之前创建的不会出现在SQL中,这是第二个问题:

photos.uuid may not be NULL: INSERT INTO "photos" ("created_at", "model_id", "image", "title", "updated_at") VALUES (?, ?, ?, ?, ?)
Run Code Online (Sandbox Code Playgroud)

这里缺乏强参数的文档,我甚至不确定如何继续.

更新 这适用于嵌套属性:

params.permit( ..., :photos_attributes => ['id', 'title', 'image', '_destroy'])
Run Code Online (Sandbox Code Playgroud)

但是看起来像Carrierwave或Nested Form应该先为Rails 4更新.它只是试图一直保存一个空图像.相同的代码(没有strong_params)在Rails 3中有效.

file-upload nested-forms carrierwave strong-parameters ruby-on-rails-4

5
推荐指数
1
解决办法
6252
查看次数

在Rails中访问未保存的父母和孩子的祖父母

我有一个表格可以将一个Parent和多个Child对象保存在一起.在初始化Child对象期间,它需要访问Grandparent.这是模型的样子:

class Grandparent
  has_many :parents, inverse_of: :grandparent
end

class Parent
  belongs_to :grandparent, inverse_of: :parents
  has_many :children, inverse_of: :parent
  accepts_nested_attributes_for :children
end

class Child
  belongs_to :parent
  delegate :grandparent, to: :parent

  # Test code
  after_initialize do
    raise 'NoParentError' unless parent.present?
    raise 'NoGrandparentError' unless grandparent.present? # Errors here!
    puts 'All good!'
  end
end
Run Code Online (Sandbox Code Playgroud)

请记住,表单用于同时保存新父项和多个子项,但我正在尝试访问祖父项对象中的信息.我读到inverse_of选项应该已经完成​​了这个伎俩,但child.grandparent仍然nil不幸.

这是实际导致失败的控制器部分:

@parent = @grandparent.parents.build(parent_params)
# prior to saving @parent
Run Code Online (Sandbox Code Playgroud)

由于某种原因,父母不知道祖父母是谁.

更新

看起来我可以通过以下代码解决该错误:

@parent = Parent.new(parent_params.merge(grandparent: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails associations nested-forms

5
推荐指数
1
解决办法
367
查看次数