Rails - Partial in another view can't access its controller -
i'm trying build profile page displays posts sent requested user, , allows visitor write post of own. because simplified example should have 2 distinct controllers: users , posts, made partials each post action render within user's show action.
directory structure views directory looks this:
- posts - _index.html.erb - _new.html.erb - users - show.html.erb ... (etc.)
section displays these partials within user's show.html.erb
:
<section> <h3>posts:</h3> <%= render '/posts/new', :post => post.new %> <%= render '/posts/index', :posts => post.where(target_id: params[:id]) %> </section>
i found out pass variables partial in render
line, , though works, it's messy , doesn't follow best practices.
ideally, i'd want these partials connected posts controller can write more complex database queries in place isn't view:
class postscontroller < applicationcontroller def new @post = post.new end def index @posts = post.where(target_id: params[:id]) end def create @post = post.new(post_params) @post.user_id = current_user.id @post.target_id = params[:post][:target_id] if @post.save redirect_to :back, notice: 'you published post!' else render new end end private def post_params params.require(:post).permit(:body) end end
currently, haven't found way of doing this. know newb question, in advance.
you attempting treat controllers models: doing post work in post controller , user work in user controller. controllers task-oriented, not model-oriented.
since want posts info in user form, it's typical gather in user controller. e.g.
class userscontroller < applicationcontroller def show ... @posts = post.where(user_id: user.id) end end
that @posts
instance variable visible in show template , partials calls. many coders prefer send explicitly through render
arguments, more functional:
<%= render '/posts/post_list', posts: @posts %>
for 1 thing it's easier refactor when can see @ glance of partial's dependencies.
Comments
Post a Comment