我正在使用Tumblr API来布局博客的所有帖子。这是我在控制器中的索引方法:
def index
# Keys given from Tumblr API
@key = '[my key]'
@secret = '[my secret]'
@oauth_token = '[my oauth token]'
@oauth_token_secret = '[my oauth token secret]'
# Sets the client that allows interfacing with Tumblr
@client = Tumblr::Client.new(
:consumer_key => @key,
:consumer_secret => @secret,
:oauth_token => @oauth_token,
:oauth_token_secret => @oauth_token_secret
)
# Make the request
@blog = "[blogname].tumblr.com"
@posts = @client.posts(@blog, :type => "photo")["posts"] #gets a posts array
# @posts = Kaminari.paginate_array(@posts["posts"]).page(params[:page]).per(10)
# # Photography posts only (other types follow the same pattern)
# @photoPosts = @myClient.posts("YOURTUMBLR.tumblr.com",
# :limit => 5,
# :type => "photo")
# @photoPosts = @photoPosts["posts"]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
这一切都很完美。但是,我希望“@blog”是动态的。因此,在视图中我需要一个用户可以输入tumblr博客的表单。我只是不知道如何连接这两个。有人有个主意吗?
谢谢!
修改 控制器:
class BlogController < ApplicationController
def index
@blog = "#{params[:blogname]}.tumblr.com"
end
def show
# Keys given from Tumblr API
@key = '[my key]'
@secret = '[my secret]'
@oauth_token = '[my oauth token]'
@oauth_token_secret = '[my oauth token secret]'
# Sets the client that allows interfacing with Tumblr
@client = Tumblr::Client.new(
:consumer_key => @key,
:consumer_secret => @secret,
:oauth_token => @oauth_token,
:oauth_token_secret => @oauth_token_secret
)
# Make the request
@posts = @client.posts(@blog, :type => "photo")["posts"]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
end
index.html.erb:
<%= form_tag( method: "get", url: "blog" ) do %>
<%= text_field_tag(:blogname) %>
<%= submit_tag %>
<% end %>
show.html.erb:
<section class="section section_grid has_no-pad">
<h1 class="is_white is_bold is_uppercase"><%= p @posts.first["blog_name"] %></h1>
<ul class="s-grid-2 has_isotope">
<% @posts.each do |post| %>
<% @type = post["type"] # the type of post %>
<% @url = post["post_url"] # the url for the post %>
<% if @type == "photo" %>
<% @pictures = post["photos"] %>
<% @pictures.each do |pic| %>
<% @pic_url = pic["original_size"]["url"] %>
<li>
<%= image_tag(@pic_url) %>
</li>
<% end %>
<% end %>
<% end %>
</ul>
</section>
路线:
Prefix Verb URI Pattern Controller#Action
blog_index GET /blog/index(.:format) blog#index
root GET / blog#index
答案 0 :(得分:1)
阅读the guide and it's chapter about forms可能会有好处。
在您的控制器中,您将从params
哈希中获取提交的值:
# controller
@blog = "#{params[:blogname]}.tumblr.com"
在模板中,您将实现一个表单以将值提交给rails app:
# index.html.erb
<%= form_tag method: :get do %>
<%= input_tag :blogname %>
<%= submit_tag %>
<% end %>
上面的代码来自我的头脑,完全未经测试。