【发布时间】:2014-03-22 02:31:10
【问题描述】:
我正在尝试将模型 User 连接到我的 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
非常感谢任何建议。 感谢您的宝贵时间。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 devise