有以下代码:
def create
@business = user.businesses.build(business_params)
if @business.save
business.set_logo_url
redirect_to admin_businesses_path, flash: { notification: 'New business has been created successfully' }
else
render 'new'
end
end
此代码起作用之前;用户" has_many"企业和所有人都很好,但现在用户" has_many:通过"而这段代码创造了一个新的业务,但没有关系!如何修复此代码以保存此业务逻辑?提前致谢。
答案 0 :(得分:4)
但现在用户" has_many:通过"
这是问题的核心--Rails很好地很多事情,但它还无法读懂思想
您遇到的问题是您正在尝试构建一个既不存在也不属于另一个关联(:through
)参数的关联。让我解释一下:
<强>的has_many 强>
当你.build
一个对象时 - 它必须与&#34; parent&#34;相关联。你正在使用的对象。 has_many
关联与父对象直接关联,允许您单独.build
:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :businesses
end
这将使您能够执行以下操作:@user.businesses.build
现在的问题是使用through
表示您的businesses
对象与您的父User
没有直接关联 - 它与之相关通过另一个对象。这意味着为了构建这个更深层的依赖对象,首先要构建through
对象:
<强>到强>
你没有给我们你的联想,但是说他们是这样的:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :business_users
has_many :businesses, through: : business_users
end
#app/models/business.rb
class Business < ActiveRecord::Base
has_many :business_users
has_many :users, through: :business_users
end
#app/models/business_user.rb
class BusinessUser < ActiveRecord::Base
belongs_to :business
belongs_to :user
end
现在,您必须以不同的方式构建关联:
@user.business_users.build.build_business
了解如何调用&#34;加入&#34;模型?
之前,您可以直接调用businesses
关联。但是当你正在通过另一个模型时,也必须构建它。
<强>表格强>
翻译成表格,您最终会得到以下设置:
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
@user.business_users.build.build_business
end
def create
@user = User.new user_params
@user.save
end
private
def user_params
params.require(:user).permit(:user, :params, business_users_attributes: [business_attributes: []])
end
end
#app/views/users/new.html.erb
<%= form_for @user do |f| %>
<%= f.fields_for :business_users do |bu| %>
<%= bu.fields_for :user do |u| %>
<%= u.text_field ... %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
答案 1 :(得分:0)
尝试在:inverse_of
模型中添加User
class User < ActiveRecord::Base
has_many :business_types, inverse_of: :user #let your relationship model to be BusinessType
has_many :businesses, :through => :business_types
...
end
也不要忘记在你的关系模型中添加accepts_nested_attributes_for
答案 2 :(得分:0)
尝试使用create而不是像这样构建:
def create
@business = user.businesses.create(business_params)
if @business.save
business.set_logo_url
redirect_to admin_businesses_path, flash: { notification: 'New business has been created successfully' }
else
render 'new'
end
end