我正在尝试将地方地址与具有Post has_one地方,地方属地与职务关系的职务相关联。我想以一个form_for完成此操作,但是在:address
form_for中使用属性Post
时遇到问题。如何分配该属性?这是我在new
页面上的代码。显然这不起作用(我也有使用ActiveStorage的图像附件):
我的观点:
<%= form_for [@post] do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.label :address %>
<%= f.text_area :address %>
<%= f.file_field :image %>
<%= f.submit %>
<% end %>
<%= button_to "back to profiles", posts_path, method: "get" %>
我的Post控制器:
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all
end
def show
end
def new
@place = Place.new
@post = Post.new
end
def create
@post = Post.create(post_params)
redirect_to post_path(@post)
end
def edit
@place = Place.find(params[:id])
end
def update
@post.update(post_params)
redirect_to post_path(@post)
end
def destroy
@post.delete(post_params)
redirect_to posts_path
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :description)
end
end
和型号:
帖子:
class Post < ApplicationRecord
belongs_to :animal, required: false
belongs_to :user, required: false
has_one_attached :image
has_one :place
accepts_nested_attributes_for :place
end
地点:
class Place < ApplicationRecord
belongs_to :post
end