【发布时间】:2015-01-28 06:19:28
【问题描述】:
我有两个模型 Author 和 Post。我希望作者能够创建帖子并在这两个模型之间建立关联。 我通常通过嵌套作者和帖子来做到这一点,因此 url 看起来像 author/:id/posts。在这种情况下,我使用 params[id] 来查找作者并且一切正常。但是,这一次,我希望帖子像 /posts/name-of-post 一样单独出现,并且与作者一样;它们将显示为作者/作者姓名。 为了创建蛞蝓,我使用了friendly_id gem。我在作者控制器上工作的蛞蝓。但是,我找不到创建帖子和创建关联的方法。
请帮助我创建帖子并将其与作者相关联。
作者模型
class Author < ActiveRecord::Base
has_many :posts
validates :name, :slug, presence: true
extend FriendlyId
friendly_id :name, use: :slugged
end
后模型
class Post < ActiveRecord::Base
belongs_to :author
end
作者控制器
def new
@author = Author.new
respond_with(@author)
end
private
def set_author
@author = Author.friendly.find(params[:id])
end
def author_params
params.require(:author).permit(:name, :slug, :bio)
end
后控制器
def new
@post = Post.new
respond_with(@post)
end
def create
@post = Post.new(post_params)
@post.save
respond_with(@post)
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body, :slug, :author_id)
end
张贴_form(苗条)
= form_for @post do |f|
- if @post.errors.any?
#error_explanation
h2 = "#{pluralize(@post.errors.count, "error")} prohibited this post from being saved:"
ul
- @post.errors.full_messages.each do |message|
li = message
.field
= f.label :title
= f.text_field :title
.field
= f.label :body
= f.text_area :body
.field
= f.label :slug
= f.text_field :slug
.field
= f.label :author
= f.text_field :author
.actions = f.submit 'Save'
当我在控制台上尝试关联时,关联工作正常。我的问题是我无法让作者的 id 自动填充到新的帖子表单视图中,并在我保存新帖子时创建关系。
【问题讨论】:
标签: ruby-on-rails-4 model-associations slug friendly-id