我确信在RoR中使用Rails并使用Rails 5.0.6(Ruby 2.3.4p301)。以下是我在过去几个小时内遇到的问题 -
我有两个表 - 位置(属性 - 地址)和评论(属性 - 标题,持续时间,正面,负面,location_id)。 location.rb是父模型,reviews.rb是子模型。
问题:
locations_controller.rb应该检查数据库中是否已存在location.address。如果是,则审核将保存在相同的location_id下。如果location.address不存在,将创建新位置和评论。这就是我使用find_or_initialize_by
方法的原因。
问题是 - 审查是命中数据库,但所有属性都是nil值。 (当我从locations_controller.rb中删除第10行和第11行时,它工作正常,只是在数据库中找不到现有的location.address。问题是,由于第10行和第11行,审核哈希值没有通过,只是以'nil'作为值创建记录。)
class Location < ApplicationRecord
has_many :reviews, inverse_of: :location
accepts_nested_attributes_for :reviews
end
class Review < ApplicationRecord
belongs_to :location, optional: true
end
01 class LocationsController < ApplicationController
02
03 def new
04 @location = Location.new
05 @location.reviews.build
06 end
07
08 def create
09 @location = Location.new(location_params)
10 @location = Location.find_or_initialize_by(address: location_params[:address])
11 @location.reviews.build
12
13 if @location.save
14 flash[:notice] = "Location has been successfully saved"
15 redirect_to location_path(@location)
16 else
17 render 'new'
18 end
19 end
20
21 def show
22 @location = Location.find(params[:id])
23 end
24
25 private
26 def location_params
27 params.require(:location).permit(:address, reviews_attributes: [:location_id, :id, :title, :duration, :positive, :negative])
28 end
29
30 end
<h1>Create a house review</h1>
<%= simple_form_for @location do |f| %>
<%= f.input :address, label: 'Enter Address', input_html: { id: 'autocomplete', size: 100 }, placeholder: 'E.g. 1 Collins Street, Melbourne, VIC 3000' %>
<%= f.simple_fields_for :reviews do |e| %>
<%= e.input :title %>
<%= e.input :duration %>
<%= e.input :positive %>
<%= e.input :negative %>
<% end %>
<%= f.button :submit %>
<% end %>
<h1>Showing selected location</h1>
<p>
Location: <%= @location.address %>
</p>
<h2>Reviews (<%= @location.reviews.count %>)</h2>
<% if @location.reviews.present? %>
<% @location.reviews.each do |review| %>
<ul>
<h3><%= review.title %></h3>
<li>Duration: <%= review.duration %></li>
<li>Positive: <%= review.positive %></li>
<li>Negative: <%= review.negative %></li>
</ul>
<% end %>
<% else %>
There are no reviews for this location.
<% end %>
答案 0 :(得分:0)
您可以使用create!更改新内容,下面是解释:
new将创建一个对象,但rails仍然不是init和id为记录,同时创建!将创建一个对象,rails将把init的id值放到记录中。如果您构建像评论一样的“子”记录,则会获得位置的初始ID,它将获得location_id值
def create
@location = Location.create!(location_params)
@location.reviews.build
# your other code
end
def create
@location = Location.find_by_address(location_params[:address])
if @location.nil?
# if nil then it's meaning @location was not found in db
# then you create it with initial id
@location = Location.create!(location_params)
# @location will get address from params automatically
end
@location.reviews.build
end