我正在尝试将模型用户连接到我的Rails应用程序中的其他模型。 我使用the gem 'devise'。
我创建了一个用户模型。 我已经有了Post模型和Comment模型。 他们像这样连接:
发布模型:
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
评论模型:
class Comment < ActiveRecord::Base
belongs_to :post
end
用户模型:
class User < ActiveRecord::Base
has_many :posts
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
路线:
devise_for :users
resources :posts do
resources :comments
end
注意:
没有用户控制器。
我想要的是什么:
我希望用户登录,他应该只能看到他的帖子。 在一个真实世界的应用程序,我知道没有意义。
当我这样做时:
rails c
User.first.posts.create(title: "foo", content: "bar")
this works
如何设法使该表格有效? 查看:
<%= form_for([@user, @user.posts.build]) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
posts_controller:
def create
@user = User.find(params[:id])
@post = @user.posts.create(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
非常感谢任何建议。 谢谢你的时间。
答案 0 :(得分:1)
尝试这样的事情:
查看:
<%= form_for @post do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
posts_controller:
class PostsController < ApplicationController
before_filter :authenticate_user!
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
private
def post_params
# whatever you need
end
end