所以,我有两种形式来创建对象。我只需Owner
即可创建name
。现在,我想创建一个Listing
name
并将其分配给Owner
。当我没有设置1-n关系时,我可以创建一个新的Listing
,但是当我Listing
belongs_to :owner
时,该表单不再有效。
型号:
class Owner
include Mongoid::Document
has_many :listings
field :name, type: String
end
class Listing
include Mongoid::Document
belongs_to :owner
field :name, type: String
end
形式:
<%= form_for @listing do |f| %>
<div class="form-group">
<%= f.label :name, "Listing Name" %>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :listing, "Owner" %>
<%= f.collection_select :owner_id, Owner.all, :id, :name, prompt: true %>
</div>
<%= f.submit class: "btn btn-primary" %>
<% end %>
控制器:
def new
@listing = Listing.new
end
def create
@listing = Listing.new(listing_params)
if @listing.save
redirect_to @listing, notice: "Listing Creation >> SUCCESS" and return
end
render :new
end
private
def listing_params
params.require(:listing).permit(:name, owner_attributes: [:name])
end
我的表单生成正确,因为我在字段中输入了每个Owner
的名称和下拉列表,但表单并未创建新的Listing
。我不明白,因为当我删除has_many
和belongs_to
关系时,表单和对象创建工作正常。
请记住,我对此非常陌生:)
谢谢!
答案 0 :(得分:0)
此处需要进行少量更改:
形式:
<%= form_for @listing do |f| %>
...
<div class="form-group">
<%= f.label :owner, "Owner" %> # :owner instead of :listing
<%= f.collection_select :owner_id, Owner.all, :id, :name, prompt: true %>
</div>
...
<% end %>
控制器:
def create
@listing = Listing.new(listing_params)
if @listing.save
redirect_to @listing, notice: "Listing Creation >> SUCCESS" and return
else
render :new
end
end
private
def listing_params
params.require(:listing).permit(:name, :owner_id)
end
如果create
请求不起作用,请恢复并添加rails日志。