开发者

Rails how to change settings in model dependent on action

I am trying to choise which height and width a youtube video should have dependent on action with an instant variable. But it does not work.

My controller:

class PublicController < ApplicationController
def index
@posts = Post.order('created_at开发者_如何学Python DESC').page(params[:page]).per(5)
@width = '600'
@height = '600'
end
end

My model:

def body_html

 auto_html self[:body_html] do
   html_escape
   image
   youtube(:width => @width, :height => @height)
   link :target => "_blank", :rel => "nofollow"
   simple_format
  end
  end


i assume body_html is you'r model's method

you're setting instance variables @width and @height in context of controller, not model

try this:

class PublicController < ApplicationController
  def index
    @posts = Post.order('created_at DESC').page(params[:page]).per(5)
    @posts.each do |post|
      post.width = '600'
      post.height = '600'
    end
  end
end

P.S.

your problem is actually wrong understanding of MVC pattern, your body_html method is way too presentational and it should be extracted into separate _post.html.erb template or whatever

that template can access all instance variables defined in controller so your original controller method can remain unchanged

P.P.S.

here are some quick code snippents:

in controller:

def index
  @posts = Post.all
  @width = @height = '600'
end

in index.html.erb

<%= render :collection => @posts %>

in _post.html.erb

...
<%= post_youtube(post, @width, @height) %>
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜