使用Rails 2.3.8
目标是创建一个Blogger,同时更新嵌套的用户模型(如果信息已更改等),或者创建一个全新的用户(如果它尚不存在).
模型:
class Blogger < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
Run Code Online (Sandbox Code Playgroud)
Blogger控制器:
def new
@blogger = Blogger.new
if user = self.get_user_from_session
@blogger.user = user
else
@blogger.build_user
end
# get_user_from_session returns existing user
# saved in session (if there is one)
end
def create
@blogger = Blogger.new(params[:blogger])
# ...
end
Run Code Online (Sandbox Code Playgroud)
形成:
<% form_for(@blogger) do |blogger_form| %>
<% blogger_form.fields_for :user do |user_form| %>
<%= user_form.label :first_name %>
<%= user_form.text_field :first_name %>
# ... other fields for …Run Code Online (Sandbox Code Playgroud) 我使用光滑的js来获取图像的滑块视图.
这是我的代码.
<div class="slider_wrap add-remove">
<%= f.fields_for :images do |image_form| %>
<%#= render 'images_fields', :f => image_form %>
<div>
<%= image_tag image_form.object.picture.url,:class=>"drop_down_link even img_prev" %>
</div>
<div class="image_upload_div">
<div class="image-upload">
<label>
<i class="fa fa-cloud-upload">
<%= image_form.file_field :picture ,:'data-role'=>"none",:onchange=>"readURL(this);" , :accept => 'image/jpeg , image/png' %>
</i>
</label>
</div>
</div>
<% end %>
<%= f.link_to_add "Add a picture", :images ,:id=>"add_pic" ,:class=>"js-add-slide", :style=>"display: none;"%>
</div>
<script>
function silder(){
slideIndex = 0;
$('.add-remove').slick({
slidesToShow: 2,
slidesToScroll: 2
});
$('.js-add-slide').on('click', function() {
$('.add-remove').slick('slickAdd');
}); …Run Code Online (Sandbox Code Playgroud) 我对rails很新,终于找到了正确的使用方法accepts_nested_attributes_for.
不过,也有在网络上一些严重的资源,谁说,使用accepts_nested_attributes_for一般是不好的做法(这样的一个).
需要进行哪些更改以避免accepts_nested_attributes_for以及在哪个文件夹中放置其他类文件(我猜需要一个额外的类).
我读到virtus适合那个.是对的吗?
这是一个仍然使用的非常基本的例子accepts_nested_attributes_for(在这里找到完整的例子):
楷模
class Person < ActiveRecord::Base
has_many :phones
accepts_nested_attributes_for :phones
end
class Phone < ActiveRecord::Base
belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)
调节器
class PeopleController < ApplicationController
def new
@person = Person.new
@person.phones.new
end
def create
@person = Person.new(person_params)
@person.save
redirect_to people_path
end
def index
@people = Person.all
end
private
def person_params
params.require(:person).permit(:name, phones_attributes: [ :id, :number ])
end
end
Run Code Online (Sandbox Code Playgroud)
查看(people/new.html.erb)
<%= form_for @person, do |f| …Run Code Online (Sandbox Code Playgroud) 我有一个Project模型,它接受Task的嵌套属性.
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks, :allow_destroy => :true
end
class Task < ActiveRecord::Base
validates_uniqueness_of :name end
Run Code Online (Sandbox Code Playgroud)
任务模型中的唯一性验证在更新Project时会出现问题.
在编辑项目时,我删除任务T1,然后添加一个同名T1的新任务,唯一性验证限制了项目的保存.
params hash看起来像
task_attributes => { {"id" =>
"1","name" => "T1", "_destroy" =>
"1"},{"name" => "T1"}}
Run Code Online (Sandbox Code Playgroud)
在销毁旧任务之前完成对任务的验证.因此验证失败.任何想法如何验证,它不会考虑任务被销毁?
我正在使用nested_form宝石作为我的AddressBook关系.当用户清空现有的值时Addr,我想删除它Addr而不是用空白保存value
class Person < ActiveRecord::Base
has_many :addrs, dependent: :destroy
attr_accessible :name, :addrs_attributes
accepts_nested_attributes_for :addrs, reject_if: :addr_blank, allow_destroy: true
def addr_blank(a)
valid? && a[:id].blank? && a[:value].blank?
end
class Addr < ActiveRecord::Base
belongs_to :person
attr_accessible :kind, :label, :value, :person_id
Run Code Online (Sandbox Code Playgroud)
我的:reject_if方法运作良好,但它没有给我我需要的一切
valid? 通过验证保持我的空白Addrsa[:id].blank? 当用户空白和现有记录时避免拒绝现在,Addr当用户空白时,我需要删除(而不是保存)现有的value.另外,我通过RESTful API公开了Persons和Addrs.我看到两种可能的选择:
params哈希以添加神奇的_destroy=1参数.IOW,模拟按下删除按钮的用户活动.Addr模型中,以便将带有空白的更新value有效地视为删除.基于这里的建议是我如何实现它:
people_controller.rb
def update
@person = Person.find(params[:id])
@person.destroy_blank_addrs(params[:person])
respond_to do |format| …Run Code Online (Sandbox Code Playgroud) 这基本上是一个嵌套的表单问题,尽管只有一个属于父模型的字段.我的数据输入表单收集模型的数据 - 但是我还需要收集一个实际进入将使用详细记录创建的父记录的数据元素/值(UserID).
AFAIK Rails希望每个表单字段都映射到一个模型,我需要创建一个我将单独使用的未绑定数据输入字段.
如何覆盖此默认行为并创建"自由格式/未绑定字段"?
TIA,BC
我正在尝试解决一个非常常见的(我认为)任务.
有三种型号:
class Product < ActiveRecord::Base
validates :name, presence: true
has_many :categorizations
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
validates :description, presence: true # note the additional field here
end
class Category < ActiveRecord::Base
validates :name, presence: true
end
Run Code Online (Sandbox Code Playgroud)
我的问题始于产品新/编辑表格.
在创建产品时,我需要检查它所属的类别(通过复选框).我知道可以通过创建名称为'product [category_ids] []'的复选框来完成.但是我还需要输入每个已检查关系的描述,这些关系将存储在连接模型(Categorization)中.
我在复杂的表格,habtm复选框等上看到了那些漂亮的Railscasts.我一直在寻找StackOverflow.但我没有成功.
我发现一篇文章描述了与我几乎完全相同的问题.最后一个答案对我来说有点意义(看起来这是正确的方法).但它实际上并不是很好(即如果验证失败).我希望类别始终以相同的顺序显示(在新的/编辑表单中;在验证之前/之后)和复选框,以便在验证失败时保持原样等等.
任何人都赞赏.我是Rails的新手(从CakePHP转换)所以请耐心等待并尽可能详细地写.请以正确的方式指出我!
谢谢.:)
forms ruby-on-rails nested-forms has-many-through ruby-on-rails-3
我正在使用Rails基于一组复杂的嵌套属性自动神奇地创建子对象.因此,我需要以非常特殊的方式嵌套参数.显然我意识到我可以用JS构建它们,但是我希望表单的顺序自动帮助构造.对于上下文,我有2列,由2 <td>秒表示.每列可以创建新记录或编辑现有记录.当然,当要修改现有记录时,必须传递记录的id.
呈现的HTML如下:
<td width="50%" style="padding-right:3%" class="logistic-details" data-type="logistics" data-typelogistics="delivery" data-instructions="test instructions" data-id="1" data-amount="20">
<span class="area-to-inject-amount-inputs" data-object="type_logistics" data-type="logistics" data-typelogistics="delivery">
<input class="labeler-response" name="type_logistics_attributes[][id]" type="hidden" value="1">
<input class="labeler-response" name="type_logistics_attributes[][instructions]" type="text" value="test instructions">
</span>
</td>
<td width="50%" style="padding-right:3%" class="logistic-details" data-type="logistics" data-typelogistics="pickup" data-instructions="" data-id="" data-amount="0">
<span class="area-to-inject-amount-inputs" data-object="type_logistics" data-type="logistics" data-typelogistics="pickup" data-actioned="charged">
<input type="hidden" name="type_logistics_attributes[][type_of_logistics]" value="pickup">
<input class="injected-amount-input" type="number" min="0" max="" placeholder="Amount" name="type_logistics_attributes[][charged_amounts_attributes][][amount]" value="20">
<span class="area-to-inject-type-of-amount">
<input type="hidden" name="type_logistics_attributes[][charged_amounts_attributes][][type_of_amount]" value="logistics">
</span>
<input class="labeler-response" name="type_logistics_attributes[][instructions]" type="text" placeholder="Enter address and instructions">
</span>
</td>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,第一个<td>是修改id为1的现有记录,而第二个<td> …
html ruby-on-rails named-parameters nested-forms nested-attributes
我有一个多层嵌套表单
User->Tasks->Prerequisites
并以相同的形式
User->Tasks->Location
位置表单工作正常,现在我正在尝试指定当前任务的先决条件.先决条件是存储在:completed_task字段中的task_id.
当我提交表单时,我在输出中收到以下错误
WARNING: Can't mass-assign protected attributes: prerequisite_attributes
对用户中的每个任务发出一个警告.
我已经完成了与此相关的所有其他问题,确保正确引用字段名称:completed_task,
将attr_accessible添加到我的模型中(它已经存在并且我将其扩展).
我不确定我还应该做什么.
我的模特看起来像
class Task < ActiveRecord::Base
attr_accessible :user_id, :date, :description, :location_id
belongs_to :user
has_one :location
accepts_nested_attributes_for :location
has_many :prerequisites
accepts_nested_attributes_for :prerequisites
end
class Prerequisite < ActiveRecord::Base
attr_accessible :completed_task
belongs_to :task
end
表格使用formtastic,我包括表格via
<%= f.semantic_fields_for :prerequisites do |builder3| %>
<%= render 'prerequisite_fields', :f=>builder3 %>
<% end %>
--- _prerequisite_fields.html.erb -----
< div class="nested-fields" >
<%= f. inputs:completed_step %>
</div>
有什么建议?
我正在尝试使用角度JS,我想从我的rails应用程序中定义的嵌套资源中获取数据.
我写了以下几行:
UserMission = $resource("/users/:user_id/user_missions/:id", {user_id: "@user_id", id: "@id"}, {update: {method: "PUT"}})
$scope.user_missions = UserMission.query()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Processing by UsersController#show as JSON
Parameters: {"id"=>"user_missions"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "user_missions"]]
Completed 404 Not Found in 10ms
ActiveRecord::RecordNotFound (Couldn't find User with id=user_missions):
app/controllers/users_controller.rb:100:in `current_resource'
app/controllers/application_controller.rb:34:in `authorize'
Run Code Online (Sandbox Code Playgroud)
我的rails路由组织如下:
resources :users do
resources :user_missions
end
Run Code Online (Sandbox Code Playgroud)
我认为这归结于我不理解"@id".它说它来自angularjs网站的"数据对象" ,我不确定这意味着什么. …
json nested-forms nested-attributes ruby-on-rails-3 angularjs
nested-forms ×10
activerecord ×1
angularjs ×1
forms ×1
html ×1
jquery ×1
json ×1
ruby ×1
slick.js ×1
slider ×1