有关rails关联的一些新手问题.
我有一个Bug模型和一个状态模型.状态基本上只是一个键/值对表.在可用的选择中,我会说Bug has_one Status最有意义.但是,根据这个
内容belongs_to ContentTemplate.回过头来看看我如何描述问题,你会发现它有效.使用belongs_to,表接受外键的责任.所以Content有一个content_template_id.而且ContentTemplate不需要任何东西.我可以随意指出它.完成.
Bug belongs_to状态更合适(因为Bug应该使用外键).在语义上,他的榜样是有道理的,但我没有.这只是一个轨道的怪癖,在这种情况下,它看起来很奇怪,或者我不理解某事/做错了?
我是Ruby on Rails的新手,我显然有一个活跃的记录关联问题,但我不能自己解决它.
鉴于三个模型类及其关联:
# application_form.rb
class ApplicationForm < ActiveRecord::Base
has_many :questions, :through => :form_questions
end
# question.rb
class Question < ActiveRecord::Base
belongs_to :section
has_many :application_forms, :through => :form_questions
end
# form_question.rb
class FormQuestion < ActiveRecord::Base
belongs_to :question
belongs_to :application_form
belongs_to :question_type
has_many :answers, :through => :form_question_answers
end
Run Code Online (Sandbox Code Playgroud)
但是当我执行控制器向应用程序表单添加问题时,我收到错误:
ActiveRecord::HasManyThroughAssociationNotFoundError in Application_forms#show
Showing app/views/application_forms/show.html.erb where line #9 raised:
Could not find the association :form_questions in model ApplicationForm
Run Code Online (Sandbox Code Playgroud)
谁能指出我做错了什么?
在本文档中(向下滚动到"单向"部分):
它表示与连接表的单向一对多关联比仅在自有实体中使用外键列更受欢迎.我的问题是,为什么它更受欢迎?
我有以下实体:
球队
@Entity
@Table
public class Team {
[..]
private Set<UserTeamRole> userTeamRoles;
/**
* @return the userTeamRoles
*/
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "team", fetch = FetchType.LAZY)
public Set<UserTeamRole> getUserTeamRoles() {
return userTeamRoles;
}
/**
* @param userTeamRoles
* the userTeamRoles to set
*/
public void setUserTeamRoles(Set<UserTeamRole> userTeamRoles) {
this.userTeamRoles = userTeamRoles;
}
Run Code Online (Sandbox Code Playgroud)
}
和
USER_TEAM_ROLE
@Entity
@Table(name = "user_team_role")
public class UserTeamRole {
@ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinColumn(name = "FK_TeamId")
public Team getTeam() {
return …
Run Code Online (Sandbox Code Playgroud) 在rails 3.2+中,您可以这样做:
SomeModel.some_scope.first_or_initialize
Run Code Online (Sandbox Code Playgroud)
这意味着您还可以:
OtherModel.some_models.first_or_initialize
Run Code Online (Sandbox Code Playgroud)
我觉得这是非常有用的,但我希望有一个first_or_build
对我的方法has_many
的关联,这将像first_or_initialize
,但还添加了一个新的纪录协会为build
在需要的时候做.
更新澄清:是的,我知道first_or_initialize
和first_or_create
.事情是,first_or_initialize
不会将初始化记录添加到关联的目标build
中,并且first_or_create
......好吧...... 创建一个记录,这不是意图.
我有一个有效的解决方案,使用关联扩展:
class OtherModel < ActiveRecord::Base
has_many :some_models do
def first_or_build( attributes = {}, options = {}, &block )
object = first_or_initialize( attributes, options, &block )
proxy_association.add_to_target( object ) if object.new_record?
object
end
end
end
Run Code Online (Sandbox Code Playgroud)
我只是想知道:
rails的新手,我正在跟踪使用rails 3.1在Agile Web开发中找到的Depot项目.一切都很好,直到我迷失了本书使用"构建"方法.
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)
Run Code Online (Sandbox Code Playgroud)
我的谷歌搜索让我明白.build方法只是一种在表格中创建行的更简洁的方法(表格之间有关联).但是在上面的代码中,我期待代码看起来像这样:
@line_item = @cart.line_items.build(product_id => params[:product_id])
Run Code Online (Sandbox Code Playgroud)
我不明白为什么作者必须存储整行产品(product = Product.find(params [:product_id]))而不是仅仅获取product_id ...
还有比我能理解的更多的东西吗?
Rails 4允许您has_many
像这样关系范围:
class Customer < ActiveRecord::Base
has_many :orders, -> { where processed: true }
end
Run Code Online (Sandbox Code Playgroud)
因此,只要您这样做,customer.orders
您只能获得已处理的订单.
但是如果我需要使where
条件动态呢?如何将参数传递给范围lambda?
例如,我只希望显示客户当前在多租户环境中登录的帐户的订单.
这是我得到的:
class Customer < ActiveRecord::Base
has_many :orders, (account) { where(:account_id => account.id) }
end
Run Code Online (Sandbox Code Playgroud)
但是,在我的控制器或视图中,我如何通过正确的帐户?在我执行以下代码时,请执行以下操作:
customers.orders
Run Code Online (Sandbox Code Playgroud)
我得到账户ID为1的所有订单,看似随意.
我似乎无法belongs_to
使用accepts_nested_attributes_for
Rails 2.3 的新工具在rails视图中生成嵌套表单以获取关系.我确实检查了许多可用的资源,看起来我的代码应该正常工作,但是fields_for
爆炸对我来说,我怀疑它与我如何配置嵌套模型有关.
我遇到的错误是一个常见的错误,可能有很多原因:
'@account[owner]' is not allowed as an instance variable name
Run Code Online (Sandbox Code Playgroud)
以下是涉及的两个模型:
class Account < ActiveRecord::Base
# Relationships
belongs_to :owner, :class_name => 'User', :foreign_key => 'owner_id'
accepts_nested_attributes_for :owner
has_many :users
end
class User < ActiveRecord::Base
belongs_to :account
end
Run Code Online (Sandbox Code Playgroud)
也许这就是我在做'rong'的地方,因为帐户可以拥有'所有者',可能是'用户',但用户只有一个'帐户',基于用户模型account_id键.
这是new.html.haml中的视图代码,它炸毁了我:
- form_for :account, :url => account_path do |account|
= account.text_field :name
- account.fields_for :owner do |owner|
= owner.text_field :name
Run Code Online (Sandbox Code Playgroud)
这是新操作的控制器代码:
class AccountsController < ApplicationController
# GET /account/new
def new
@account …
Run Code Online (Sandbox Code Playgroud) 我正在使用Ruby on Rails v3.2.2.我想解决与使用accepts_nested_attributes_for
和validates_associated
RoR方法时验证外键有关的问题.也就是说,我有以下模型类:
class Article < ActiveRecord::Base
has_many :category_associations, :foreign_key => 'category_id'
accepts_nested_attributes_for :category_associations, :reject_if => lambda { |attributes| attributes[:category_id].blank? }
validates_associated :category_associations
end
class CategoryAssociation < ActiveRecord::Base
belongs_to :article, :foreign_key => 'article_id'
belongs_to :category, :foreign_key => 'category_id'
validates :article_id, :presence => true
validates :category_id, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
......我有以下控制器动作:
class ArticlesController < ApplicationController
def new
@article = Article.new
5.times { @article.category_associations.build }
# ...
end
def create
@article = Article.new(params[:article])
if @article.save
# ... …
Run Code Online (Sandbox Code Playgroud) 我需要在同一个模型中做两个关联.哪里:
团队 has_many
用户
现在,我想要那个团队 has_one
负责人
这个"领导者"将是一个用户
我试图使用,has_one throught
但我认为这种关联不起作用.
Leader.rb
class Leader < ActiveRecord::Base
belongs_to :user
belongs_to :team
Run Code Online (Sandbox Code Playgroud)
Team.rb
class Team < ActiveRecord::Base
has_one :user, through: :leader
end
Run Code Online (Sandbox Code Playgroud)
User.rb
class User < ActiveRecord::Base
belongs_to :team
has_one :captain
end
Run Code Online (Sandbox Code Playgroud)
并在第27行附近得到以下错误:
NoMethodError in TeamsController#create
26 def create
**27 @team = current_user.teams.create(team_params)**
28 @team.save
29 respond_with(@team)
30 current_user.update(team_id: @team.id)
Run Code Online (Sandbox Code Playgroud) associations ×10
activerecord ×3
hibernate ×2
one-to-many ×2
belongs-to ×1
database ×1
foreign-keys ×1
has-many ×1
jpa ×1
model ×1
models ×1
ruby ×1
scopes ×1
validation ×1