当我发布表单以创建带有子评论的新查询时(在应用程序中,查询可以有多个评论),评论不会被构建.它在删除状态验证时有效.所以它与构建和保存事物的顺序有关.如何保留验证并保持代码清洁?
(以下是一个示例,因此可能无法完全运行)
车型/ inquiry.rb
class Inquiry < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
Run Code Online (Sandbox Code Playgroud)
车型/ comment.rb
class Comment < ActiveRecord::Base
belongs_to :inquiry
belongs_to :user
validates_presence_of :user_id, :inquiry_id
Run Code Online (Sandbox Code Playgroud)
控制器/ inquiry_controller.rb
expose(:inquiries)
expose(:inquiry)
def new
inquiry.comments.build :user => current_user
end
def create
# inquiry.save => false
# inquiry.valid? => false
# inquiry.errors => {:"comments.inquiry_id"=>["can't be blank"]}
end
Run Code Online (Sandbox Code Playgroud)
意见/查询/ new.html.haml
= simple_form_for inquiry do |f|
= f.simple_fields_for :comments do |c|
= c.hidden_field :user_id
= c.input :body, :label => 'Comment'
= f.button :submit
Run Code Online (Sandbox Code Playgroud)
数据库架构
create_table "inquiries", …Run Code Online (Sandbox Code Playgroud) 我有一个Item资源和一个Owner资源.
rails g scaffold Item name:string
rails g scaffold Owner name:string
class Item < ActiveRecord::Base
has_one :owner
accepts_nested_attributes_for :owner
end
class Owner < ActiveRecord::Base
belongs_to :item
end
Run Code Online (Sandbox Code Playgroud)
我的问题是我无法创建引用现有Owner对象的新Item对象.
In /db/migrate/create_owners.rb
def self.up
...
t.integer :item_id
end
rake db:migrate
rails c
ruby-1.9.2-p0 > o= Owner.create(:name => "Test")
=> #<Owner id: 1, name: "Test", created_at: "...", updated_at: "...">
ruby-1.9.2-p0 > i= Item.create(:owner_attributes => {"id" => Owner.last.id.to_s})
ActiveRecord::RecordNotFound: Couldn't find Owner with ID=1 for Item with ID=
Run Code Online (Sandbox Code Playgroud)
我知道这Item.create(:owner_id => "1")可以在这种情况下工作,但不幸的是,这在我的应用程序中不是一个可行的解决方案.这是因为我正在动态添加和删除嵌套属性,例如,需要使用一个现有的Owner对象和一个新的Owner对象创建一个新的Item对象.
我找到了这些链接,但如果这是一个功能或rails中的错误,则无法解决: …
我的申请中有父/子关系
class Polling
has_many :alerts, :dependent => :destroy
class Alert
belongs_to :polling
Run Code Online (Sandbox Code Playgroud)
在我的警报索引页面上,我需要显示每个父项的一些数据,这会产生两个查询
Alert Load (6.1ms) SELECT * FROM (SELECT * FROM "ALERTS" INNER JOIN "POLLINGS" ON "POLLINGS"."ID" = "ALERTS"."POLLING_ID" ORDER BY "ALERTS"."ID" DESC) WHERE ROWNUM <= 1
Polling Load (1.8ms) SELECT "POLLINGS".* FROM "POLLINGS" WHERE "POLLINGS"."ID" = 10113 AND ROWNUM <= 1
Run Code Online (Sandbox Code Playgroud)
显然,这会使页面加载时间非常可怕,因为它必须遍历每个页面并拉动父对象.
我尝试过一些东西,比如
> Alert.joins(:polling).where(...)
> Alert.includes(:polling).where(...)
> Alert.joins(:polling).select('*').where(...)
Run Code Online (Sandbox Code Playgroud)
每当我访问索引页面时,每次收到两个不同的查询.每个Alert一个,然后另一个获取其父数据.如何在一行上执行此操作,以便在我提取警报时,我还可以获取其关联的父数据?从另一端似乎没有办法解决这个问题,因为如果我这样做Pollings.where(...),就不会把孩子当成一个群体.
现在,我有一个服务器调用踢回以下Ruby哈希:
{
"id"=>"-ct",
"factualId"=>"",
"outOfBusiness"=>false,
"publishedAt"=>"2012-03-09 11:02:01",
"general"=>{
"name"=>"A Cote",
"timeZone"=>"EST",
"desc"=>"À Côté is a small-plates restaurant in Oakland's charming
Rockridge district. Cozy tables surround large communal tables in both
the main dining room and on the sunny patio to create a festive atmosphere.
Small plates reflecting the best of seasonal Mediterranean cuisine are served
family-style by a friendly and knowledgeable staff.\nMenu items are paired with
a carefully chosen selection of over 40 wines by the glass as well as …Run Code Online (Sandbox Code Playgroud) 我阅读了很多相关的帖子,但找不到为什么它不适合我.我还有一个"无法大量分配受保护的属性:个人资料"......我做错了什么?
我有一个User模型和一个具有一对一关系的相关Profile模型.这里的用户模型(简化)
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :profile_attributes, :profile_id
has_secure_password
has_one :profile
accepts_nested_attributes_for :profile
end
Run Code Online (Sandbox Code Playgroud)
Profile模型
class Profile < ActiveRecord::Base
attr_accessible :bio, :dob, :firstname, :gender, :lastname, :user_id
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
我的用户控制器
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
def create
@user = User.new(params[:user])
@user.build_profile
respond_to do |format|
if @user.save
format.html { redirect_to @user, flash: {success: 'User was successfully created. Welcome !'} }
format.json …Run Code Online (Sandbox Code Playgroud) nested-forms mass-assignment nested-attributes ruby-on-rails-3.2
我在GitHub上找到了https://github.com/dgeb/ember_data_example下的ember-data的一个很好的工作示例,并尝试通过嵌套资源('has_many:comments')扩展它.在原始示例中,每次打开编辑视图时都会创建一个新事务,如果编辑模式处于离开状态,则会提交/回滚该事务.
我想在content.comments中添加一条新评论我无法做到并且因为"内容"已经在事务中而出现错误(错误:断言失败:一旦记录发生变化,您就无法将其移动到另一个事务中).
这个想法我试图意识到错了,我必须采取另一种方式吗?
App.EditContactController = Em.Controller.extend({
content: null,
addComment: function () {
// ERROR here:
this.get('content.comments').addObject(App.Comment.createRecord({body: ''}));
},
enterEditing: function() {
this.transaction = this.get('store').transaction();
if (this.get('content.id')) {
this.transaction.add(this.get('content'));
} else {
this.set('content', this.transaction.createRecord(App.Contact, {}));
}
},
exitEditing: function() {
if (this.transaction) {
this.transaction.rollback();
this.transaction = null;
}
},
updateRecord: function() {
// commit and then clear the transaction (so exitEditing doesn't attempt a rollback)
this.transaction.commit();
this.transaction = null;
}
});
Run Code Online (Sandbox Code Playgroud) 我的问题是我遇到了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
我的问题有点类似于问题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
错误消息不会转换我的嵌套模型属性,因为它被定义为单数,但在错误消息中它查找复数.
我有一个模型'人',其中has_many:地址.此Person模型接受"地址"的嵌套属性.我只创建地址和Person模型.
我的语言环境文件看起来像
en:
activerecord:
models:
person:
one: "Person"
other: "People"
address:
one: 'Address'
other: 'Addresses'
attributes:
person:
first_name: 'First name'
last_name: 'Last name'
middle_name: 'Middel name'
address:
street: street
city: city
country: country
Run Code Online (Sandbox Code Playgroud)
并为错误消息:
en:
errors: &errors
format: ! '%{attribute} %{message}'
messages:
blank: can't be blank
Run Code Online (Sandbox Code Playgroud)
它适用于单个模型但具有嵌套属性我遇到了验证消息的问题.
由于消息显示如下:
@messages=
{:first_name=>["can't be blank"],
:last_name=>["can't be blank"],
:"addresses.street"=>["can't be blank"],
:"addresses.city"=>["can't be blank"]}>
Run Code Online (Sandbox Code Playgroud)
查找找不到addresses.street的转换,因为它只是yml文件中的address.street.
我怎样才能找到address.street,当它查找address.street而不加倍我的所有条目?
所以我的问题是:
https://gist.github.com/panSarin/4a221a0923927115584a
当我保存这个表格时,我得到像标题中的错误
NoMethodError (undefined method `updated?' for
#ActiveRecord::Associations::HasOneAssociation:0x00000008fcacf8>):
Run Code Online (Sandbox Code Playgroud)
我检查没有多态关联 - 它是相同的.
当父模型(在那种情况下是BusinessClient)有belongs_to它然后它工作正常.但我无法相信我不能拥有孩子们所拥有的建筑parent_id.知道我应该改变什么使其有效?
nested-forms ×3
activerecord ×1
ember-data ×1
ember.js ×1
has-one ×1
hash ×1
localization ×1
ruby ×1
simple-form ×1
transactions ×1
validation ×1