我在验证时试图在我的子模型中访问我的父模型.我在has_one上发现了一些关于反属性的东西,但是我的Rails 2.3.5无法识别它,所以它一定没有进入发行版.我不确定它是否正是我所需要的.
我想根据父属性有条件地验证子项.我的父模型已经创建.如果在我对父项进行update_attributes时尚未创建子项,则它无权访问父项.我想知道如何访问这个父母.它应该很简单,像parent.build_child这样设置子模型的parent_id,为什么在为accepts_nested_attributes_for构建子项时没有这样做?
例如:
class Parent < AR
has_one :child
accepts_nested_attributes_for :child
end
class Child < AR
belongs_to :parent
validates_presence_of :name, :if => :some_method
def some_method
return self.parent.some_condition # => undefined method `some_condition' for nil:NilClass
end
end
Run Code Online (Sandbox Code Playgroud)
我的表格是标准的:
<% form_for @parent do |f| %>
<% f.fields_for :child do |c| %>
<%= c.name %>
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
使用更新方法
def update
@parent = Parent.find(params[:id])
@parent.update_attributes(params[:parent]) # => this is where my child validations take place
end
Run Code Online (Sandbox Code Playgroud) 我有一个Rails模型的嵌套属性,并且关联验证由于某种原因失败.我没有使用accepts_nested_attributes_for,但我做的事情非常相似.
class Project < ActiveRecord::Base
has_many :project_attributes
def name
project_attributes.find_by_name("name")
end
def name=(val)
attribute = project_attributes.find_by_name("name")
if attribute
attribute.value = val
else
project_attributes.build(:name=>"name", :value=>val)
end
end
end
class ProjectAttribute < ActiveRecord::Base
belongs_to :project
validates_presence_of :name
validates_uniqueness_of :name, :scope => :project_id
validates_presence_of :project_id, :unless => lambda {|attribute| attribute.project.try(:valid?)}
validates_associated :project
end
Run Code Online (Sandbox Code Playgroud)
这是一个人为的例子,但与我想要做的类似.我已经看了一下accepts_nested_attributes_for做了什么,它使用了构建方法,我认为它会将构建的属性与项目相关联.
我还查看了accepts_nested_attributes_for子关联验证失败,这给了我validates_presence_of :unless=>valid?
有关如何使其工作的任何想法?
我的模型结构如下所示:
董事会has_many主题.主题has_many帖子.
应用程序/模型/ board.rb
class Board < ActiveRecord::Base
has_many :topics
end
Run Code Online (Sandbox Code Playgroud)
应用程序/模型/ topic.rb
class Topic < ActiveRecord::Base
belongs_to :user
belongs_to :board
has_many :posts
accepts_nested_attributes_for :posts
validates :title, presence: true, length: { maximum: 255 }
validates :user_id, presence: true
validates :board_id, presence: true
...
end
Run Code Online (Sandbox Code Playgroud)
应用程序/模型/ post.rb
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :topic
validates :user_id, presence: true
validates :topic_id, presence: true
validates :content, length: { minimum: 8 }
end
Run Code Online (Sandbox Code Playgroud)
以下是我创建新主题的观点.fields_for部分用于在新帖子上创建:内容
应用程序/视图/主题/ new.html.erb
<div>
<%= form_for [@board, @topic] do |f| …Run Code Online (Sandbox Code Playgroud) ruby-on-rails associations nested-resources nested-attributes ruby-on-rails-4