【问题标题】:Rails: Associating two different models when not using params[:id]Rails:不使用参数时关联两个不同的模型[:id]
【发布时间】: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


    【解决方案1】:

    您需要以与之前创建帖子相同的方式创建帖子。您希望能够单独查看帖子,与作者无关,这一事实不需要更改您创建它们的方式。

    因此,例如,对于 url /author_slug/posts/new,您的控制器操作可能如下所示:

    # posts_controller.rb
    def new
      @author = Author.friendly_find(params[:author_id])
      @post = @author.posts.build
    end
    

    然后,在posts/post-slug-from-friendly-id 的无作者路线上,您只需要从帖子中获取作者即可。比如:

    # routes.rb
    get 'posts/:post_slug', to: posts#anonymous_show
    
    # posts_controller.rb
    def anonymous_show
      @post = Post.friendly_find(params[:post_slug])
      @author = @post.author
    end
    

    【讨论】:

    • 感谢您的回复。当人们访问博客时,我试图不在 URL 上显示作者。如果我这样做,则 params[:author_id] 为 nil,并且我找不到与该作者关联的帖子。如果参数上没有 author_id,如何获取该作者的帖子?
    • 一旦博客或帖子记录与作者ID一起保存,您可以从该记录中获取作者。查看更新的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多