关联数据库如何获取其外键?

发布于 2024-09-30 01:00:35 字数 946 浏览 0 评论 0原文

我对默认控制器做了很多修改,现在我无法在创建时填充我的 user_id 。

我很好奇它是如何填充的。如果您有兴趣,请查看我的路线和模型关联,然后最后我将向您展示生成的参数。最终结果是没有添加 user_id

routes

resources :users do
  resources :posts do
    collection do
      get :view
    end
  end
end

models

#Post.rb
belongs_to                    :user, :touch => true                    
#User.rb
has_many :posts

我导航到这个网址..

http://localhost:3001/users/1/posts/new

并放置我的帖子,params 返回这个:

{"commit"=>"save", "post"=>{"name"=>"hell hath no furry", "category"=>"vegan", "url"=>"www.reddit.com", "text"=>"", "is_link"=>"1"}, "authenticity_token"=>"aYnSLgJ9E6MaM6iSkRrCyyiMZj06oLdybTMkNqss8FA=", "utf8"=>"✓", "action"=>"create", "controller"=>"posts"}

这之前是有效的,不知道为什么它不再关联它们。

有什么想法吗?

I did a bunch of gutting to my default controllers and now I can't get my user_id to populate on create.

I was curious how that gets populated. If you're interested, take a look at my routes, and model assocations, and then at then end I'll show you the resulting params..The end result is no user_id being added.

routes

resources :users do
  resources :posts do
    collection do
      get :view
    end
  end
end

models

#Post.rb
belongs_to                    :user, :touch => true                    
#User.rb
has_many :posts

I navigate to this url..

http://localhost:3001/users/1/posts/new

and place my post, and the params return this :

{"commit"=>"save", "post"=>{"name"=>"hell hath no furry", "category"=>"vegan", "url"=>"www.reddit.com", "text"=>"", "is_link"=>"1"}, "authenticity_token"=>"aYnSLgJ9E6MaM6iSkRrCyyiMZj06oLdybTMkNqss8FA=", "utf8"=>"✓", "action"=>"create", "controller"=>"posts"}

This was working before, not sure why its not associating them anymore.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-10-07 01:00:35

在您的 form_for 中,您是否传递了@user?

form_for([@user, @post]) do

也许这会有所帮助:

http:// www.gatezero.org/blog/2008/4/30/rails-nested-resources-and-form_for.html

In your form_for, are you passing in the @user?

form_for([@user, @post]) do

Maybe this will help:

http://www.gatezero.org/blog/2008/4/30/rails-nested-resources-and-form_for.html

沐歌 2024-10-07 01:00:35

嗯,我不喜欢回答自己的问题,但我找到了这个解决方案,并且想知道这是否是实现此目标的可接受的方式。

在我的 def create 控制器中,我这样做:

@post = current_user.posts.create(params[:post])

而不是这样:

@post = Post.new(params[:post])

Hmm I don't like answering my own questions, but I found this solution, and was wondering if this is an acceptable way of accomplishing this.

In my controller for def create , I do this :

@post = current_user.posts.create(params[:post])

instead of this :

@post = Post.new(params[:post])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文