【发布时间】:2015-10-06 02:45:43
【问题描述】:
我已尝试找出无法保存 community_id 背后的问题,希望有人可以帮助我。
模型
用户
has_one :profile
has_many :communities, dependent: :destroy
has_many :comment, dependent: :destroy
社区
extend FriendlyId
friendly_id :title, use: [:slugged, :finders]
has_many :comments
belongs_to :user
评论
belongs_to :user
belongs_to :community
belongs_to :profile
控制器
社区
def index
@communities = Community.all
@comment = Comment.new
@comments = Comment.all
end
def create
@community = Community.new(community_params)
@community.user_id = session[:user_id]
if @community.save
flash[:notice] = "Post Created"
else
flash[:alert] = "Error post not created"
end
redirect_to "/"
end
def new
@community = Community.new
end
def edit
@community = Community.friendly.find(params[:id])
end
def show
@comment = Comment.new
@comments = Comment.all
@community = Community.friendly.find(params[:id])
@current_user = User.find(session[:user_id])
end
def update
@community = Community.friendly.find(params[:id])
if @community.update(params[:comment])
flash[:notice] = "post updated"
else
flash[:alert] = "post not updated"
end
end
def destroy
@community = Community.friendly.find(params[:id])
if @community.destroy
flash[:notice] = "Post was thrown away"
else
flash[:alert] = "Post was not deleted"
end
redirect_to "/"
end
private
def community_params
params.require(:community).permit(:user_id, :title, :bio)
end
评论
def index
@comments = Comment.all
end
def create
@comment = Comment.new(comment_params)
@comment.user_id = session[:user_id]
if @comment.save && @comment.community_id
flash[:notice] = "Comment has been posted"
else
flash[:alert] = @comment.errors.full_messages
end
redirect_to :back
end
def new
@comment = Comment.new
end
def show
@comment = Comment.find(params[:id])
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to :back
end
private
def comment_params
params.require(:comment).permit(:text, :user_id, :community_id, :profile_id)
end
观看次数
cmets/_new
<%= form_for @comment do |f| %>
<%= f.hidden_field :community_id %>
<%= f.text_area :text, placeholder: "Enter New Comment Here ...", :cols => 50, :rows => 3, :class => 'text_field_message', :id => 'new_comment' %>
<%= f.submit :class => 'new_comment_button' %>
<% end %>
每当我检查我的控制台时,我都会注意到 user_id 已在评论中注册,但 community_id 为 nil。有人可以指出我正确的方向或帮助我了解我在哪里犯了错误。感谢您的所有帮助。
【问题讨论】:
-
如果 current_user 有多个社区,社区 id 应该有什么值?
-
@BroiSatse 注意到我的整个代码都没有写。我的值写为
-
而
community_id的值从何而来?代码中没有任何内容可以解释您希望如何将这两条记录绑定在一起。我最初的想法是你有嵌套资源,但你的 cmets 控制器的其余部分似乎与这个想法不同。 -
我看不到分配给
hidden_field community_id的任何值 -
您在哪个视图中调用该部分形式?
标签: ruby-on-rails model-view-controller