【发布时间】:2014-09-11 17:10:31
【问题描述】:
我尝试自己学习 Rails。我使用脚手架和资源生成器创建了简单的应用程序。我创建了具有用户和文章模型的博客应用程序。一切都很好,直到我想显示在用户个人资料中关联的用户的文章。我相信控制器有问题。文章/节目也没有错。
用户模型:
class User < ActiveRecord::Base
has_many :articles
end
文章型号:
class Article < ActiveRecord::Base
belongs_to :user
end
用户控制器:
before_action :set_user, only: [:show, :edit, :update, :destroy]
def show
@article = @user.articles.find(params[:user_id])
end
文章控制器:
class ArticlesController < ApplicationController
def new
@user = User.find(params[:user_id])
@article = @user.articles.new
end
def create
@user = User.find(params[:user_id])
@article = @user.articles.new(params.require(:article).permit!)
if @article.save
redirect_to user_article_path(:user_id)
else
render :new
end
end
def show
@user = User.find(params[:id])
@article = @user.articles.find(params[:user_id])
end
end
用户视图:
<p id="notice"><%= notice %></p>
<p>
<strong>Username:</strong>
<%= @user.username %>
</p>
<p>
<strong>Email:</strong>
<%= @user.email %>
</p>
<p>
<strong>Password:</strong>
<%= @user.password %>
</p>
<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>
<%= link_to 'new article', new_user_article_path(@user) %><br>
<%= @article.title %><br>
<%= @article.body %>
<% end %>
路线:
Rails.application.routes.draw do
resources :users do
resources :articles
end
end
【问题讨论】:
标签: ruby-on-rails-4 model associations views render